------------------------------------------------------------------------------01 Sep2023-----------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_consultation_statistics"(integer, integer, timestamp without time zone, timestamp without time zone);

CREATE OR REPLACE FUNCTION public."udf_consultation_statistics"(
	providerid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone)
    RETURNS TABLE("AccountId" integer, "DoctorName" text, "AppointmentCount" bigint , "AdmissionCount" bigint ,"LabCount" bigint ,  "PharmacyCount" bigint,"ScanCount" bigint ) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
 
begin
 return query 
 with accountdata as (
select a."ProviderId",a."FullName" "DoctorName"
from "Provider" a
JOIN "Account" ac on ac."ReferenceId"=a."ProviderId" and ac."RoleId"=3
JOIN "LocationAccountMap" LAM on LAM."AccountId"=ac."AccountId" 
where case when providerId is null then 1=1 else 
	 a."ProviderId"=providerId end 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE 
	 LAM."LocationId"=locationId END
)


,AppointmentTotal as (	
  select Count(*) as "AppointmentTotal",p."ProviderId",p."FullName" from "Appointment" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId"  and p."Active"<>false
	 where 
		case when providerId is null then 1=1 else ap."ProviderId"=providerId end    
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
		
	and ap."Active"<>false and ap."AppointmentId" is not null  
	 and ap."Status" <> 'C' and	
	case when "fromDate" is null then 1=1 
	else (ap."CreatedDate" >= "fromDate" and ap."CreatedDate" <= "toDate") end
			group by  p."ProviderId"
)
,AdmissionTotal as (
	select Count(*) as "AdmissionTotal",p."ProviderId",p."FullName" from "Admission" ad 
left join "Provider" p on p."ProviderId"=ad."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ad."ProviderId"=providerId end  
		AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and ad."Active"<>false 
	and case when "fromDate" is null then 1=1 
	else (ad."CreatedDate" >= "fromDate" and ad."CreatedDate" <= "toDate")  end
			group by  p."ProviderId"	
	
)
,LabTotal as (select Count(*) as "LabTotal",p."ProviderId",p."FullName" from "NewLabBookingHeader" ar  
left join "Provider" p on p."ProviderId"=ar."DoctorId" and p."Active"<>false
			 
	where case when providerId is null then 1=1 else ar."DoctorId"=providerId end    
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ar."LocationId"=locationId END
	AND case when "fromDate" is null then 1=1 
	else (ar."CreatedDate" >= "fromDate" and ar."CreatedDate" <= "toDate")  end
			group by  p."ProviderId")
			
,PharmaTotal as (select Count(*) as "PharmaTotal",p."ProviderId",p."FullName" from "PharmacySaleHeader" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ap."ProviderId"=providerId end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ap."SaleDate" >= "fromDate" and ap."SaleDate" <= "toDate")  end
			group by  p."ProviderId"	
)	
,ScanTotal as (
	select Count(*) as "ScanTotal",p."ProviderId",p."FullName" from "BookScanAppointment" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ap."ProviderId"=providerId end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ap."CreatedDate" >= "fromDate" and ap."CreatedDate" <= "toDate")  end
			group by  p."ProviderId"
)	
  select distinct  a."ProviderId",a."DoctorName"::text "DoctorName",
						  ap."AppointmentTotal",
						  ad."AdmissionTotal",
						  lb."LabTotal",
						  pa."PharmaTotal",
						  sa."ScanTotal"

from accountdata a
 left join AppointmentTotal ap on ap."ProviderId"=a."ProviderId"
left join AdmissionTotal ad on ad."ProviderId"=a."ProviderId"
left join LabTotal lb on lb."ProviderId"=a."ProviderId"
left join PharmaTotal pa on pa."ProviderId"=a."ProviderId"
left join ScanTotal sa on sa."ProviderId"=a."ProviderId"
;
	end
$BODY$;

alter table if exists "GynEncounter"
add column if not exists "OutSideTests" text COLLATE pg_catalog."default";

CREATE TABLE IF NOT EXISTS public."ReferralForm"
(
    "ReferralFormId" integer NOT NULL DEFAULT nextval('"ReferralForm_ReferralFormId_seq"'::regclass),
    "ReferralDoctor" character varying(50) COLLATE pg_catalog."default" NOT NULL,
    "Reason" text COLLATE pg_catalog."default",
    "RequiredDate" date,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ConsultantDoctor" character varying(50) COLLATE pg_catalog."default",
    "Opinion" text COLLATE pg_catalog."default",
    "Active" boolean DEFAULT true,
    "AppointmentId" integer NOT NULL,
    "ProviderId" integer,
    "PatientId" integer,
    "ReferralDoctorId" integer,
    "Time" text COLLATE pg_catalog."default",
    "AdmissionId" integer,
    CONSTRAINT "PK_ReferralFormId" PRIMARY KEY ("ReferralFormId"),
   
    CONSTRAINT "FK_ReferralForm_PatientId" FOREIGN KEY ("PatientId")
        REFERENCES public."Patient" ("PatientId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ReferralForm_ProviderId" FOREIGN KEY ("ProviderId")
        REFERENCES public."Provider" ("ProviderId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "ReferralForm_ReferralDoctorId_fkey" FOREIGN KEY ("ReferralDoctorId")
        REFERENCES public."Provider" ("ProviderId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);

-----------------------------------------------------------------------------Shiva 01Sep2023-------------------------------------------------------------------------

DROP FUNCTION IF EXISTS public.udf_emloyee_new_revenue(integer, integer, integer, date, date);

CREATE OR REPLACE FUNCTION public.udf_emloyee_new_revenue(
	accountid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer,
	roleid integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date)
    RETURNS TABLE("AccountId" integer, "EmployeeName" text, "RoleName" character varying, "RegistrationCashTotal" numeric, "RegistrationCardTotal" numeric, "RegistrationUPITotal" numeric, "RegistrationOnlineTotal" numeric, "RegistrationChequeTotal" numeric, "RegistrationPaytmTotal" numeric, "RegistrationNotPaidTotal" numeric, "RegistrationOtherTotal" numeric, "RegistrationCardSwipeTotal" numeric, "RegistrationCardStandAloneTotal" numeric, "RegistrationCardUPITotal" numeric, "RegistrationCardGpayTotal" numeric, "RegistrationCashDrawerTotal" numeric, "RegistrationCashChequeTotal" numeric, "RegistrationCashDDTotal" numeric, "RegistrationWalletPaytmOfflineTotal" numeric, "RegistrationWalletPhonePeOfflineTotal" numeric, "RegistrationCashRemoteDepositTotal" numeric, "RegistrationWalletPaytmDQRTotal" numeric, registrationamount numeric, "AppointmentCashTotal" numeric, "AppointmentCardTotal" numeric, "AppointmentUPITotal" numeric, "AppointmentOnlineTotal" numeric, "AppointmentChequeTotal" numeric, "AppointmentPaytmTotal" numeric, "AppointmentNotPaidTotal" numeric, "AppointmentOtherTotal" numeric, "AppointmentCardSwipeTotal" numeric, "AppointmentCardStandAloneTotal" numeric, "AppointmentCardUPITotal" numeric, "AppointmentCardGpayTotal" numeric, "AppointmentCashDrawerTotal" numeric, "AppointmentCashChequeTotal" numeric, "AppointmentCashDDTotal" numeric, "AppointmentWalletPaytmOfflineTotal" numeric, "AppointmentWalletPhonePeOfflineTotal" numeric, "AppointmentCashRemoteDepositTotal" numeric, "AppointmentWalletPaytmDQRTotal" numeric, "AppointmentAmount" numeric, "AdmissionCashTotal" numeric, "AdmissionCardTotal" numeric, "AdmissionUPITotal" numeric, "AdmissionOnlineTotal" numeric, "AdmissionChequeTotal" numeric, "AdmissionPaytmTotal" numeric, "AdmissionNotPaidTotal" numeric, "AdmissionOtherTotal" numeric, "AdmissionCardSwipeTotal" numeric, "AdmissionCardStandAloneTotal" numeric, "AdmissionCardUPITotal" numeric, "AdmissionCardGpayTotal" numeric, "AdmissionCashDrawerTotal" numeric, "AdmissionCashChequeTotal" numeric, "AdmissionCashDDTotal" numeric, "AdmissionWalletPaytmOfflineTotal" numeric, "AdmissionWalletPhonePeOfflineTotal" numeric, "AdmissionCashRemoteDepositTotal" numeric, "AdmissionWalletPaytmDQRTotal" numeric, "AdmissionAmount" numeric, "LabCash" numeric, "LabCard" numeric, "LabUPI" numeric, "LabOnline" numeric, "LabCheque" numeric, "LabPaytm" numeric, "LabNotPaidTotal" numeric, "LabOtherTotal" numeric, "LabCardSwipeTotal" numeric, "LabCardStandAloneTotal" numeric, "LabCardUPITotal" numeric, "LabCardGpayTotal" numeric, "LabCashDrawerTotal" numeric, "LabCashChequeTotal" numeric, "LabCashDDTotal" numeric, "LabWalletPaytmOfflineTotal" numeric, "LabWalletPhonePeOfflineTotal" numeric, "LabCashRemoteDepositTotal" numeric, "LabWalletPaytmDQRTotal" numeric, "LabAmount" numeric, "PharmacySaleCash" numeric, "PharmacySaleCard" numeric, "PharmacySaleUPI" numeric, "PharmacySaleOnline" numeric, "PharmacySaleCheque" numeric, "PharmacySalePaytm" numeric, "PharmacySaleNotPaidTotal" numeric, "PharmacySaleOtherTotal" numeric, "PharmacySaleCardSwipeTotal" numeric, "PharmacySaleCardStandAloneTotal" numeric, "PharmacySaleCardUPITotal" numeric, "PharmacySaleCardGpayTotal" numeric, "PharmacySaleCashDrawerTotal" numeric, "PharmacySaleCashChequeTotal" numeric, "PharmacySaleCashDDTotal" numeric, "PharmacySaleWalletPaytmOfflineTotal" numeric, "PharmacySaleWalletPhonePeOfflineTotal" numeric, "PharmacySaleCashRemoteDepositTotal" numeric, "PharmacySaleWalletPaytmDQRTotal" numeric, "PharmacyAmount" numeric, "TotalCash" numeric, "TotalCard" numeric, "TotalUPI" numeric, "TotalOnline" numeric, "TotalCheque" numeric, "TotalPaytm" numeric, "NotPaidTotal" numeric, "OtherTotal" numeric, "CardSwipeTotal" numeric, "CardStandAloneTotal" numeric, "CardUPITotal" numeric, "CardGpayTotal" numeric, "CashDrawerTotal" numeric, "CashChequeTotal" numeric, "CashDDTotal" numeric, "WalletPaytmOfflineTotal" numeric, "WalletPhonePeOfflineTotal" numeric, "CashRemoteDepositTotal" numeric, "WalletPaytmDQRTotal" numeric, "Total" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
 return query 

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"  
join "Role" rol on rol."RoleId" = a."RoleId" --and lower(rol."RoleName") <> lower('Patient')
where a."RoleId"<>4
and	case when accountid is null then 1=1 else a."AccountId"=accountid end   
and	case when roleid is null then 1=1 else a."RoleId"=roleid end 	
AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE LAM."LocationId"=locationId END
)
,patientRegistrationamount as(
 select a."AccountId",
	sum(A."CashTotal") "RegistrationCashTotal"
	,sum(A."CardTotal") "RegistrationCardTotal",
 	sum(A."UPITotal") "RegistrationUPITotal",
	sum(A."OnlineTotal") "RegistrationOnlineTotal",
 	sum(A."ChequeTotal") "RegistrationChequeTotal",
	sum(A."PaytmTotal") "RegistrationPaytmTotal",
	sum(A."NotPaidTotal") "RegistrationNotPaidTotal",
	sum(A."OtherTotal") "RegistrationOtherTotal",
	sum(A."CardSwipeTotal") "RegistrationCardSwipeTotal",
	sum(A."CardStandAloneTotal") "RegistrationCardStandAloneTotal",
	sum(A."CardUPITotal") "RegistrationCardUPITotal",
	sum(A."CardGpayTotal") "RegistrationCardGpayTotal",
	sum(A."CashDrawerTotal") "RegistrationCashDrawerTotal",
	sum(A."CashChequeTotal") "RegistrationCashChequeTotal",
	sum(A."CashDDTotal") "RegistrationCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "RegistrationWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "RegistrationWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "RegistrationCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "RegistrationWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")
	+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
 	 
	registrationamount
 	from ( 
	select  a."CreatedBy"  "AccountId",   
   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
   case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal",
	case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
   case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
   case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
   case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
   case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"	
		from "Receipt" A
   join "Patient" p on  p."PatientId" =A."RespectiveId"          
   where A."ReceiptTypeId"=1 and p."Active" <> false and A."Active"<>false and A."RespectiveId" is not null
		and case when accountid is null then 1=1 else a."CreatedBy"=accountid end  
		and case when (locationId IS NULL OR locationId=0) THEN 1=1 ELSE p."LocationId"=locationId END 
		and		case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end		
	) a group by  a."AccountId"	
)

,actappointmentamount as (
	
	select a."AccountId",
	sum(A."CashTotal") "AppointmentCashTotal",
	sum(A."CardTotal") "AppointmentCardTotal",
	sum(A."UPITotal") "AppointmentUPITotal",
	sum(A."OnlineTotal") "AppointmentOnlineTotal",
	sum(A."ChequeTotal") "AppointmentChequeTotal",
	sum(A."PaytmTotal") "AppointmentPaytmTotal",
	sum(A."NotPaidTotal") "AppointmentNotPaidTotal",
	sum(A."OtherTotal") "AppointmentOtherTotal",
	sum(A."CardSwipeTotal") "AppointmentCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AppointmentCardStandAloneTotal",
	sum(A."CardUPITotal") "AppointmentCardUPITotal",
	sum(A."CardGpayTotal") "AppointmentCardGpayTotal",
	sum(A."CashDrawerTotal") "AppointmentCashDrawerTotal",
	sum(A."CashChequeTotal") "AppointmentCashChequeTotal",
	sum(A."CashDDTotal") "AppointmentCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AppointmentWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AppointmentWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AppointmentCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AppointmentWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")
	+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	appointmentamount
	from (
   select  a."CreatedBy"  "AccountId",   
   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
   case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal",
	case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
    case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
	case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
    case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
    case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"	
	from "Receipt" A
    join "Appointment" ap on  ap."AppointmentId" =A."RespectiveId"  
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
    and ap."Active" =true	
   where case when accountid is null then 1=1 else a."CreatedBy"=accountid end  and A."ReceiptTypeId"=1 	
	and A."Active"<>false and A."RespectiveId" is not null
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
	and coalesce(A."IsRefunded",false) <>true and ap."Status" <> 'C' and	
	case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end	
	)a 
	group by  a."AccountId"	 
)

,refundappointmentamount as (
	select a."AccountId" ,
	sum(A."CashTotal") "AppointmentRefCashTotal",
	sum(A."CardTotal") "AppointmentRefCardTotal",
	sum(A."UPITotal") "AppointmentRefUPITotal",
	sum(A."OnlineTotal") "AppointmentRefOnlineTotal",
	sum(A."ChequeTotal") "AppointmentRefChequeTotal",
	sum(A."PaytmTotal") "AppointmentRefPaytmTotal",
	sum(A."NotPaidTotal") "AppointmentRefNotPaidTotal",
	sum(A."OtherTotal") "AppointmentRefOtherTotal",
	sum(A."CardSwipeTotal") "AppointmentRefCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AppointmentRefCardStandAloneTotal",
	sum(A."CardUPITotal") "AppointmentRefCardUPITotal",
	sum(A."CardGpayTotal") "AppointmentRefCardGpayTotal",
	sum(A."CashDrawerTotal") "AppointmentRefCashDrawerTotal",
	sum(A."CashChequeTotal") "AppointmentRefCashChequeTotal",
	sum(A."CashDDTotal") "AppointmentRefCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AppointmentRefWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AppointmentRefWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AppointmentRefCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AppointmentRefWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	
	 refappointmentamount 
	from (
    select  a."CreatedBy"  "AccountId",
	 case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
      case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal" ,
	 case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
     case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
	case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
    case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
   case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"
		 from "Receipt" A
    join "Appointment" ap on ap."AppointmentId" =A."RespectiveId"  
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
   and ap."Status" <> 'C'   and ap."Active" =true
	
   where case when accountid is null then 1=1 else a."CreatedBy"=accountid end   
	and A."Active"<>false and A."RespectiveId" is not null 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
	and coalesce(A."IsRefunded",false) = true and 
	case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end
	) a
	group by  a."AccountId"	
	
)

,appointmentamount as (
select  A."AccountId",
	coalesce(A."AppointmentCashTotal",0) - coalesce(B."AppointmentRefCashTotal",0) as "AppointmentCashTotal" ,
	coalesce(A."AppointmentCardTotal",0) - coalesce(B."AppointmentRefCardTotal",0) as "AppointmentCardTotal" ,
	coalesce(A."AppointmentUPITotal",0) - coalesce(B."AppointmentRefUPITotal",0) as "AppointmentUPITotal" ,
	coalesce(A."AppointmentOnlineTotal",0) - coalesce(B."AppointmentRefOnlineTotal",0) as "AppointmentOnlineTotal" ,
	coalesce(A."AppointmentChequeTotal",0) - coalesce(B."AppointmentRefChequeTotal",0) as "AppointmentChequeTotal" ,
	coalesce(A."AppointmentPaytmTotal",0) - coalesce(B."AppointmentRefPaytmTotal",0) as "AppointmentPaytmTotal" ,
	coalesce(A."AppointmentNotPaidTotal",0) - coalesce(B."AppointmentRefNotPaidTotal",0) as "AppointmentNotPaidTotal" ,
	coalesce(A."AppointmentOtherTotal",0) - coalesce(B."AppointmentRefOtherTotal",0) as "AppointmentOtherTotal" ,
	coalesce(A."AppointmentCardSwipeTotal",0) - coalesce(B."AppointmentRefCardSwipeTotal",0) as "AppointmentCardSwipeTotal" ,
	coalesce(A."AppointmentCardStandAloneTotal",0) - coalesce(B."AppointmentRefCardStandAloneTotal",0) as "AppointmentCardStandAloneTotal" ,
	coalesce(A."AppointmentCardUPITotal",0) - coalesce(B."AppointmentRefCardUPITotal",0) as "AppointmentCardUPITotal" ,
	coalesce(A."AppointmentCardGpayTotal",0) - coalesce(B."AppointmentRefCardGpayTotal",0) as "AppointmentCardGpayTotal" ,
	coalesce(A."AppointmentCashDrawerTotal",0) - coalesce(B."AppointmentRefCashDrawerTotal",0) as "AppointmentCashDrawerTotal" ,
	coalesce(A."AppointmentCashChequeTotal",0) - coalesce(B."AppointmentRefCashChequeTotal",0) as "AppointmentCashChequeTotal" ,
	coalesce(A."AppointmentCashDDTotal",0) - coalesce(B."AppointmentRefCashDDTotal",0) as "AppointmentCashDDTotal" ,
	coalesce(A."AppointmentWalletPaytmOfflineTotal",0) - coalesce(B."AppointmentRefWalletPaytmOfflineTotal",0) as "AppointmentWalletPaytmOfflineTotal" ,
	coalesce(A."AppointmentWalletPhonePeOfflineTotal",0) - coalesce(B."AppointmentRefWalletPhonePeOfflineTotal",0) as "AppointmentWalletPhonePeOfflineTotal" ,
	coalesce(A."AppointmentCashRemoteDepositTotal",0) - coalesce(B."AppointmentRefCashRemoteDepositTotal",0) as "AppointmentCashRemoteDepositTotal" ,
		coalesce(A."AppointmentWalletPaytmDQRTotal",0) - coalesce(B."AppointmentRefWalletPaytmDQRTotal",0) as "AppointmentWalletPaytmDQRTotal" ,
	coalesce(A.appointmentamount,0) - coalesce(B.refappointmentamount,0) as "AppointmentAmount" from actappointmentamount A
	left join refundappointmentamount B on A."AccountId"=B."AccountId"
	
	
)

,actadmissionamount as (
	
	select a."AccountId" , 
	sum(A."CashTotal") "AdmissionCashTotal",
	sum(A."CardTotal") "AdmissionCardTotal",
	 sum(A."UPITotal") "AdmissionUPITotal",
	sum(A."OnlineTotal") "AdmissionOnlineTotal",
	 sum(A."ChequeTotal") "AdmissionChequeTotal",
	sum(A."PaytmTotal") "AdmissionPaytmTotal",
	sum(A."NotPaidTotal") "AdmissionNotPaidTotal",
	sum(A."OtherTotal") "AdmissionOtherTotal",
	sum(A."CardSwipeTotal") "AdmissionCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AdmissionCardStandAloneTotal",
	sum(A."CardUPITotal") "AdmissionCardUPITotal",
	sum(A."CardGpayTotal") "AdmissionCardGpayTotal",
	sum(A."CashDrawerTotal") "AdmissionCashDrawerTotal",
	sum(A."CashChequeTotal") "AdmissionCashChequeTotal",
	sum(A."CashDDTotal") "AdmissionCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AdmissionWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AdmissionWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AdmissionCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AdmissionWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	"AdmissionAmount"
	from (
select adr."CreatedBy" "AccountId" ,
     case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
     case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal"	,
	  case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
       case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal"	,	
       case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
       case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal"	,
       case when adr."PayTypeId"=7 then coalesce(adr."Cost",0) else 0 end "NotPaidTotal",
        case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end  "OtherTotal",
        case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardSwipeTotal",
        case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end  "CardStandAloneTotal",
        case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal",
        case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end  "CardGpayTotal",
        case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end  "CashDrawerTotal",
        case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
        case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
        case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
        case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
        case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end  "CashRemoteDepositTotal",
        case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end   "WalletPaytmDQRTotal"
												  
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when accountid is null then 1=1 else adr."CreatedBy"=accountid end 	
	and adr."ReceiptTypeId"=1  and adr."Active"<>false  and adr."AdmissionId" is not null
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	)a
	group by  a."AccountId"	
)

,refadmissionamount as (
	select a."AccountId" , 
	sum(A."CashTotal") "AdmissionRefCashTotal",
	sum(A."CardTotal") "AdmissionRefCardTotal",
	sum(A."UPITotal") "AdmissionRefUPITotal",
	sum(A."OnlineTotal") "AdmissionRefOnlineTotal",
	sum(A."ChequeTotal") "AdmissionRefChequeTotal",
	sum(A."PaytmTotal") "AdmissionRefPaytmTotal",
	sum(A."NotPaidTotal") "AdmissionRefNotPaidTotal",
	sum(A."OtherTotal") "AdmissionRefOtherTotal",
	sum(A."CardSwipeTotal") "AdmissionRefCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AdmissionRefCardStandAloneTotal",
	sum(A."CardUPITotal") "AdmissionRefCardUPITotal",
	sum(A."CardGpayTotal") "AdmissionRefCardGpayTotal",
	sum(A."CashDrawerTotal") "AdmissionRefCashDrawerTotal",
	sum(A."CashChequeTotal") "AdmissionRefCashChequeTotal",
	sum(A."CashDDTotal") "AdmissionRefCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AdmissionRefWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AdmissionRefWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AdmissionRefCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AdmissionRefWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")

	"AdmissionRefAmount" 
	from (
select adr."CreatedBy" "AccountId"  ,  
		case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
        case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal" ,
		case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
        case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal" ,
		case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
        case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal" ,
		case when adr."PayTypeId"=7 then coalesce(adr."Cost",0) else 0 end "NotPaidTotal",
        case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end  "OtherTotal",
        case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardSwipeTotal",
        case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end  "CardStandAloneTotal",
        case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal",
        case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end  "CardGpayTotal",
        case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end  "CashDrawerTotal",
        case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
        case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
        case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
        case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
        case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end  "CashRemoteDepositTotal",
        case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end   "WalletPaytmDQRTotal"
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when accountid is null then 1=1 else adr."CreatedBy"=accountid end 	
	 and adr."IsRefunded" = true   and adr."Active"<>false  and adr."AdmissionId" is not null
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	)a
	group by  a."AccountId"	
)

,admissionamount as (
select A."AccountId" ,
	coalesce(A."AdmissionCashTotal",0) - coalesce(B."AdmissionRefCashTotal",0) "AdmissionCashTotal",
	coalesce(A."AdmissionCardTotal",0) - coalesce(B."AdmissionRefCardTotal",0) "AdmissionCardTotal",
	coalesce(A."AdmissionUPITotal",0) - coalesce(B."AdmissionRefUPITotal",0) "AdmissionUPITotal",
	coalesce(A."AdmissionOnlineTotal",0) - coalesce(B."AdmissionRefOnlineTotal",0) "AdmissionOnlineTotal",
	coalesce(A."AdmissionChequeTotal",0) - coalesce(B."AdmissionRefChequeTotal",0) "AdmissionChequeTotal",
	coalesce(A."AdmissionPaytmTotal",0) - coalesce(B."AdmissionRefPaytmTotal",0) "AdmissionPaytmTotal",
	coalesce(A."AdmissionNotPaidTotal",0) - coalesce(B."AdmissionRefNotPaidTotal",0) as "AdmissionNotPaidTotal" ,
	coalesce(A."AdmissionOtherTotal",0) - coalesce(B."AdmissionRefOtherTotal",0) as "AdmissionOtherTotal" ,
	coalesce(A."AdmissionCardSwipeTotal",0) - coalesce(B."AdmissionRefCardSwipeTotal",0) as "AdmissionCardSwipeTotal" ,
	coalesce(A."AdmissionCardStandAloneTotal",0) - coalesce(B."AdmissionRefCardStandAloneTotal",0) as "AdmissionCardStandAloneTotal" ,
	coalesce(A."AdmissionCardUPITotal",0) - coalesce(B."AdmissionRefCardUPITotal",0) as "AdmissionCardUPITotal" ,
	coalesce(A."AdmissionCardGpayTotal",0) - coalesce(B."AdmissionRefCardGpayTotal",0) as "AdmissionCardGpayTotal" ,
	coalesce(A."AdmissionCashDrawerTotal",0) - coalesce(B."AdmissionRefCashDrawerTotal",0) as "AdmissionCashDrawerTotal" ,
	coalesce(A."AdmissionCashChequeTotal",0) - coalesce(B."AdmissionRefCashChequeTotal",0) as "AdmissionCashChequeTotal" ,
	coalesce(A."AdmissionCashDDTotal",0) - coalesce(B."AdmissionRefCashDDTotal",0) as "AdmissionCashDDTotal" ,
	coalesce(A."AdmissionWalletPaytmOfflineTotal",0) - coalesce(B."AdmissionRefWalletPaytmOfflineTotal",0) as "AdmissionWalletPaytmOfflineTotal" ,
	coalesce(A."AdmissionWalletPhonePeOfflineTotal",0) - coalesce(B."AdmissionRefWalletPhonePeOfflineTotal",0) as "AdmissionWalletPhonePeOfflineTotal" ,
	coalesce(A."AdmissionCashRemoteDepositTotal",0) - coalesce(B."AdmissionRefCashRemoteDepositTotal",0) as "AdmissionCashRemoteDepositTotal" ,
		coalesce(A."AdmissionWalletPaytmDQRTotal",0) - coalesce(B."AdmissionRefWalletPaytmDQRTotal",0) as "AdmissionWalletPaytmDQRTotal" ,
	coalesce(A."AdmissionAmount",0) - coalesce(B."AdmissionRefAmount",0) "AdmissionAmount"
   from actadmissionamount A
	left join refadmissionamount B on A."AccountId"=B."AccountId"	 

)
,LabAmount as ( 
select a."AccountId",
	sum(a."Cash") "LabCash",
	sum(a."Card") "LabCard" ,
	sum(a."UPI") "LabUPI",
	sum(a."Online") "LabOnline" ,
	sum(a."Cheque") "LabCheque",
	sum(a."Paytm") "LabPaytm" ,
	sum(a."NotPaidTotal") "LabNotPaidTotal",
	sum(a."OtherTotal") "LabOtherTotal",
	sum(a."CardSwipeTotal") "LabCardSwipeTotal",
	sum(a."CardStandAloneTotal") "LabCardStandAloneTotal",
	sum(a."CardUPITotal") "LabCardUPITotal",
	sum(a."CardGpayTotal") "LabCardGpayTotal",
	sum(a."CashDrawerTotal") "LabCashDrawerTotal",
	sum(a."CashChequeTotal") "LabCashChequeTotal",
	sum(a."CashDDTotal") "LabCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "LabWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "LabWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "LabCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "LabWalletPaytmDQRTotal",
	sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")

	"LabAmount"
	from(
select 	a."AccountId",							  
	case when ar."PayTypeId"=1 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."OverallNetAmount",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."OverallNetAmount",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."OverallNetAmount",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."OverallNetAmount",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."OverallNetAmount",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."OverallNetAmount",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."OverallNetAmount",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."OverallNetAmount",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."OverallNetAmount",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."OverallNetAmount",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."OverallNetAmount",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."OverallNetAmount",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."OverallNetAmount",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."OverallNetAmount",0) else 0 end   "WalletPaytmDQRTotal"
from "Account" a		
join "NewLabBookingHeader" ar on ar."CreatedBy" = a."AccountId" and ar."Active" <> false
where case when accountid is null then 1=1 else a."AccountId"=accountid end 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ar."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end)a
group by a."AccountId" )

,PharmaSaleAmount as (
	
select a."AccountId", sum(a."Cash") "PharmaSaleCash",
	sum(a."Card") "PharmaSaleCard" ,
	sum(a."UPI") "PharmaSaleUPI",
	sum(a."Online") "PharmaSaleOnline" ,
	sum(a."Cheque") "PharmaSaleCheque",
	sum(a."Paytm") "PharmaSalePaytm" ,
	sum(a."NotPaidTotal") "PharmaSaleNotPaidTotal",
	sum(a."OtherTotal") "PharmaSaleOtherTotal",
	sum(a."CardSwipeTotal") "PharmaSaleCardSwipeTotal",
	sum(a."CardStandAloneTotal") "PharmaSaleCardStandAloneTotal",
	sum(a."CardUPITotal") "PharmaSaleCardUPITotal",
	sum(a."CardGpayTotal") "PharmaSaleCardGpayTotal",
	sum(a."CashDrawerTotal") "PharmaSaleCashDrawerTotal",
	sum(a."CashChequeTotal") "PharmaSaleCashChequeTotal",
	sum(a."CashDDTotal") "PharmaSaleCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "PharmaSaleWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "PharmaSaleWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "PharmaSaleCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "PharmaSaleWalletPaytmDQRTotal",
	 sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")

	"PharmaSaleAmount" 
	from (
select a."AccountId", 
	 case when ar."PayTypeId"=1 then  coalesce(ar."Cost",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."Cost",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."Cost",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."Cost",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."Cost",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."Cost",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."Cost",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."Cost",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."Cost",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."Cost",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."Cost",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."Cost",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."Cost",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."Cost",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."Cost",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."Cost",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."Cost",0) else 0 end   "WalletPaytmDQRTotal"
from "Account" a
join "Receipt" ar on ar."CreatedBy" = a."AccountId" and ar."ReceiptAreaTypeId"=1
join "PharmacySaleHeader" ps on ps."PharmacySaleHeaderId"=ar."RespectiveId"
where case when accountid is null then 1=1 else a."AccountId"=accountid end
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ps."LocationId"=locationId END 
		and case when "fromDate" is null then 1=1 
else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end	
	)a
group by a."AccountId"
)
,PharmaReturnAmount as (
select a."AccountId", 
	sum(a."Cash") "PharmaReturnCash",
	sum(a."Card") "PharmaReturnCard" ,
	sum(a."UPI") "PharmaReturnUPI",
	sum(a."Online") "PharmaReturnOnline" ,
	sum(a."Cheque") "PharmaReturnCheque",
	sum(a."Paytm") "PharmaReturnPaytm" ,
	sum(a."NotPaidTotal") "PharmaReturnNotPaidTotal",
	sum(a."OtherTotal") "PharmaReturnOtherTotal",
	sum(a."CardSwipeTotal") "PharmaReturnCardSwipeTotal",
	sum(a."CardStandAloneTotal") "PharmaReturnCardStandAloneTotal",
	sum(a."CardUPITotal") "PharmaReturnCardUPITotal",
	sum(a."CardGpayTotal") "PharmaReturnCardGpayTotal",
	sum(a."CashDrawerTotal") "PharmaReturnCashDrawerTotal",
	sum(a."CashChequeTotal") "PharmaReturnCashChequeTotal",
	sum(a."CashDDTotal") "PharmaReturnCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "PharmaReturnWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "PharmaReturnWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "PharmaReturnCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "PharmaReturnWalletPaytmDQRTotal",
	 sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")
 
	"PharmaReturnAmount"
	from(
select a."AccountId", 
	 case when ar."PayTypeId"=1 then  coalesce(ar."Cost",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."Cost",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."Cost",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."Cost",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."Cost",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."Cost",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."Cost",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."Cost",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."Cost",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."Cost",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."Cost",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."Cost",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."Cost",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."Cost",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."Cost",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."Cost",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."Cost",0) else 0 end   "WalletPaytmDQRTotal"
		
							   
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"
left join "Receipt" ar on ar."CreatedBy" = a."AccountId" and ar."ReceiptAreaTypeId"=7
left join "SaleReturnHeader" sh on sh."SaleReturnHeaderId" = ar."RespectiveId"
where case when accountid is null then 1=1 else ar."CreatedBy"=accountid end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE LAM."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end	
	)a
group by a."AccountId"
)

 ,PharmaAmount as (
 select a."AccountId", 	
 	 coalesce(a."PharmaSaleCash",0) - coalesce(b."PharmaReturnCash",0) as  "PharmaSaleCash" ,
	 coalesce(a."PharmaSaleCard",0) - coalesce(b."PharmaReturnCard",0) as  "PharmaSaleCard" ,
	 coalesce(a."PharmaSaleUPI",0) - coalesce(b."PharmaReturnUPI",0) as  "PharmaSaleUPI" ,
	 coalesce(a."PharmaSaleOnline",0) - coalesce(b."PharmaReturnOnline",0) as  "PharmaSaleOnline" ,
	 coalesce(a."PharmaSaleCheque",0) - coalesce(b."PharmaReturnCheque",0) as  "PharmaSaleCheque" ,
	 coalesce(a."PharmaSalePaytm",0) - coalesce(b."PharmaReturnPaytm",0) as  "PharmaSalePaytm" ,
	 coalesce(a."PharmaSaleNotPaidTotal",0) - coalesce(b."PharmaReturnNotPaidTotal",0) as  "PharmaSaleNotPaidTotal" ,
	 coalesce(a."PharmaSaleOtherTotal",0) - coalesce(b."PharmaReturnOtherTotal",0) as  "PharmaSaleOtherTotal" ,
	 coalesce(a."PharmaSaleCardSwipeTotal",0) - coalesce(b."PharmaReturnCardSwipeTotal",0) as  "PharmaSaleCardSwipeTotal" ,
	 coalesce(a."PharmaSaleCardStandAloneTotal",0) - coalesce(b."PharmaReturnCardStandAloneTotal",0) as  "PharmaSaleCardStandAloneTotal" ,
	 coalesce(a."PharmaSaleCardUPITotal",0) - coalesce(b."PharmaReturnCardUPITotal",0) as  "PharmaSaleCardUPITotal" ,
	 coalesce(a."PharmaSaleCardGpayTotal",0) - coalesce(b."PharmaReturnCardGpayTotal",0) as  "PharmaSaleCardGpayTotal" ,
	 coalesce(a."PharmaSaleCashDrawerTotal",0) - coalesce(b."PharmaReturnCashDrawerTotal",0) as  "PharmaSaleCashDrawerTotal" ,
	 coalesce(a."PharmaSaleCashDDTotal",0) - coalesce(b."PharmaReturnCashDDTotal",0) as  "PharmaSaleCashDDTotal" ,
	 coalesce(a."PharmaSaleCashChequeTotal",0) - coalesce(b."PharmaReturnCashChequeTotal",0) as  "PharmaSaleCashChequeTotal" ,
	 coalesce(a."PharmaSaleWalletPaytmOfflineTotal",0) - coalesce(b."PharmaReturnWalletPaytmOfflineTotal",0) as  "PharmaSaleWalletPaytmOfflineTotal" ,
	 coalesce(a."PharmaSaleWalletPhonePeOfflineTotal",0) - coalesce(b."PharmaReturnWalletPhonePeOfflineTotal",0) as  "PharmaSaleWalletPhonePeOfflineTotal" ,
	 coalesce(a."PharmaSaleCashRemoteDepositTotal",0) - coalesce(b."PharmaReturnCashRemoteDepositTotal",0) as  "PharmaSaleCashRemoteDepositTotal" ,
	 coalesce(a."PharmaSaleWalletPaytmDQRTotal",0) - coalesce(b."PharmaReturnWalletPaytmDQRTotal",0) as  "PharmaSaleWalletPaytmDQRTotal" ,
	coalesce(a."PharmaSaleAmount",0) - coalesce(b."PharmaReturnAmount",0) as  "PharmaAmount" 
 from PharmaSaleAmount a
 	left join PharmaReturnAmount b on a."AccountId"=b."AccountId"
 )
 
select distinct  a."AccountId",a."EmployeeName",a."RoleName",
                     pr."RegistrationCashTotal",pr."RegistrationCardTotal",pr."RegistrationUPITotal",pr."RegistrationOnlineTotal",pr."RegistrationChequeTotal",pr."RegistrationPaytmTotal",
						 pr.  "RegistrationNotPaidTotal" ,pr. "RegistrationOtherTotal" ,pr. "RegistrationCardSwipeTotal" ,pr."RegistrationCardStandAloneTotal" ,
				    pr. "RegistrationCardUPITotal" ,pr."RegistrationCardGpayTotal" ,pr."RegistrationCashDrawerTotal" ,pr."RegistrationCashChequeTotal" ,
				    pr. "RegistrationCashDDTotal" ,pr."RegistrationWalletPaytmOfflineTotal" ,pr."RegistrationWalletPhonePeOfflineTotal" ,pr."RegistrationCashRemoteDepositTotal" ,
				      pr. "RegistrationWalletPaytmDQRTotal" ,
						pr."registrationamount",
						  ap."AppointmentCashTotal",ap."AppointmentCardTotal",ap."AppointmentUPITotal",ap."AppointmentOnlineTotal",ap."AppointmentChequeTotal",ap."AppointmentPaytmTotal",
						 ap."AppointmentNotPaidTotal" ,ap."AppointmentOtherTotal" ,ap."AppointmentCardSwipeTotal" ,ap."AppointmentCardStandAloneTotal" ,
				   ap."AppointmentCardUPITotal" ,ap."AppointmentCardGpayTotal" ,ap."AppointmentCashDrawerTotal" ,ap."AppointmentCashChequeTotal" ,
				    ap."AppointmentCashDDTotal" ,ap."AppointmentWalletPaytmOfflineTotal" ,ap."AppointmentWalletPhonePeOfflineTotal" ,ap."AppointmentCashRemoteDepositTotal" ,
				     ap."AppointmentWalletPaytmDQRTotal" ,
						ap."AppointmentAmount",
						  ad."AdmissionCashTotal",ad."AdmissionCardTotal",ad."AdmissionUPITotal",ad."AdmissionOnlineTotal",ad."AdmissionChequeTotal",ad."AdmissionPaytmTotal",
						 ad."AdmissionCardUPITotal" ,ad."AdmissionCardGpayTotal" ,ad."AdmissionCashDrawerTotal" ,ad."AdmissionCashChequeTotal" ,
						 ad."AdmissionNotPaidTotal" ,ad."AdmissionOtherTotal" ,ad."AdmissionCardSwipeTotal" ,ad."AdmissionCardStandAloneTotal" ,
				    ad."AdmissionCashDDTotal" ,ad."AdmissionWalletPaytmOfflineTotal" ,ad."AdmissionWalletPhonePeOfflineTotal" ,ad."AdmissionCashRemoteDepositTotal" ,
				     ad."AdmissionWalletPaytmDQRTotal" , 
						ad."AdmissionAmount",
						  lb."LabCash", lb."LabCard",lb."LabUPI", lb."LabOnline",lb."LabCheque", lb."LabPaytm",
						    lb."LabNotPaidTotal" , lb."LabOtherTotal" , lb."LabCardSwipeTotal" , lb."LabCardStandAloneTotal" ,
						 lb."LabCardUPITotal" ,lb."LabCardGpayTotal" ,lb."LabCashDrawerTotal" ,lb."LabCashChequeTotal" ,
				   lb."LabCashDDTotal" ,lb."LabWalletPaytmOfflineTotal" ,lb."LabWalletPhonePeOfflineTotal" ,lb."LabCashRemoteDepositTotal" ,
				     lb."LabWalletPaytmDQRTotal" 
						,lb."LabAmount",
sum(pa."PharmaSaleCash") over(partition by a."AccountId")  "PharmacySaleCash",
sum(pa."PharmaSaleCard") over(partition by a."AccountId") 	"PharmacySaleCard",
sum(pa."PharmaSaleUPI") over(partition by a."AccountId")  "PharmacySaleUPI",
sum(pa."PharmaSaleOnline") over(partition by a."AccountId") 	"PharmacySaleOnline",
sum(pa."PharmaSaleCheque") over(partition by a."AccountId")  "PharmacySaleCheque",
sum(pa."PharmaSalePaytm") over(partition by a."AccountId") 	"PharmacySalePaytm",

sum(pa."PharmaSaleNotPaidTotal") over(partition by a."AccountId") 	"PharmacySaleNotPaidTotal",
sum(pa."PharmaSaleOtherTotal") over(partition by a."AccountId") 	"PharmacySaleOtherTotal",
sum(pa."PharmaSaleCardSwipeTotal") over(partition by a."AccountId") 	"PharmacySaleCardSwipeTotal",
sum(pa."PharmaSaleCardStandAloneTotal") over(partition by a."AccountId") 	"PharmacySaleCardStandAloneTotal",
sum(pa."PharmaSaleCardUPITotal") over(partition by a."AccountId") 	"PharmacySaleCardUPITotal",
sum(pa."PharmaSaleCardGpayTotal") over(partition by a."AccountId") 	"PharmacySaleCardGpayTotal",
sum(pa."PharmaSaleCashDrawerTotal") over(partition by  a."AccountId") 	"PharmacySaleCashDrawerTotal",
sum(pa."PharmaSaleCashChequeTotal") over(partition by a."AccountId") 	"PharmacySaleCashChequeTotal",
sum(pa."PharmaSaleCashDDTotal") over(partition by a."AccountId") 	"PharmacySaleCashDDTotal",
sum(pa."PharmaSaleWalletPaytmOfflineTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPaytmOfflineTotal",
sum(pa."PharmaSaleWalletPhonePeOfflineTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPhonePeOfflineTotal",
sum(pa."PharmaSaleCashRemoteDepositTotal") over(partition by a."AccountId") 	"PharmacySaleCashRemoteDepositTotal",
sum(pa."PharmaSaleWalletPaytmDQRTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPaytmDQRTotal",
sum(pa."PharmaAmount") over(partition by a."AccountId") "PharmacyAmount",
coalesce(pr."RegistrationCashTotal",0)+coalesce(ap."AppointmentCashTotal",0)+coalesce(ad."AdmissionCashTotal",0)+coalesce(lb."LabCash",0)+coalesce(sum(pa."PharmaSaleCash") over(partition by a."AccountId") ,0) "TotalCash",
coalesce(pr."RegistrationCardTotal",0)+	coalesce(ap."AppointmentCardTotal",0)+coalesce(ad."AdmissionCardTotal",0)+coalesce(lb."LabCard",0)+coalesce(sum(pa."PharmaSaleCard") over(partition by a."AccountId"),0)  "TotalCard",	
coalesce(pr."RegistrationUPITotal",0)+	coalesce(ap."AppointmentUPITotal",0)+coalesce(ad."AdmissionUPITotal",0)+coalesce(lb."LabUPI",0)+coalesce(sum(pa."PharmaSaleUPI") over(partition by a."AccountId") ,0) "TotalUPI",
coalesce(pr."RegistrationOnlineTotal",0)+coalesce(ap."AppointmentOnlineTotal",0)+coalesce(ad."AdmissionOnlineTotal",0)+coalesce(lb."LabOnline",0)+coalesce(sum(pa."PharmaSaleOnline") over(partition by a."AccountId"),0)  "TotalOnline",	
coalesce(pr."RegistrationChequeTotal",0)+coalesce(ap."AppointmentChequeTotal",0)+	coalesce(ad."AdmissionChequeTotal",0)+coalesce(lb."LabCheque",0)+coalesce(sum(pa."PharmaSaleCheque") over(partition by a."AccountId") ,0) "TotalCheque",
coalesce(pr."RegistrationPaytmTotal",0)+coalesce(ap."AppointmentPaytmTotal",0)+	coalesce(ad."AdmissionPaytmTotal",0)+coalesce(lb."LabPaytm",0)+coalesce(sum(pa."PharmaSalePaytm") over(partition by a."AccountId"),0)  "TotalPaytm",	
coalesce(pr."RegistrationNotPaidTotal",0)+coalesce(ap."AppointmentPaytmTotal",0)+coalesce(ad."AdmissionNotPaidTotal",0)+coalesce(lb."LabNotPaidTotal",0)+coalesce(sum(pa."PharmaSaleNotPaidTotal") over(partition by a."AccountId"),0)  "TotalNotPaid",
coalesce(pr."RegistrationOtherTotal",0)+coalesce(ap."AppointmentOtherTotal",0)+	coalesce(ad."AdmissionOtherTotal",0)+coalesce(lb."LabOtherTotal",0)+coalesce(sum(pa."PharmaSaleOtherTotal") over(partition by a."AccountId"),0)  "TotalOther",
coalesce(pr."RegistrationCardSwipeTotal",0)+coalesce(ap."AppointmentCardSwipeTotal",0)+	coalesce(ad."AdmissionCardSwipeTotal",0)+coalesce(lb."LabCardSwipeTotal",0)+coalesce(sum(pa."PharmaSaleCardSwipeTotal") over(partition by a."AccountId"),0)  "CardSwipeTotal",
coalesce(pr."RegistrationCardStandAloneTotal",0)+coalesce(ap."AppointmentCardStandAloneTotal",0)+coalesce(ad."AdmissionCardStandAloneTotal",0)+coalesce(lb."LabCardStandAloneTotal",0)+coalesce(sum(pa."PharmaSaleCardStandAloneTotal") over(partition by a."AccountId"),0)  "CardStandAloneTotal",
coalesce(pr."RegistrationCardUPITotal",0)+coalesce(ap."AppointmentCardUPITotal",0)+coalesce(ad."AdmissionCardUPITotal",0)+coalesce(lb."LabCardUPITotal",0)+coalesce(sum(pa."PharmaSaleCardUPITotal") over(partition by a."AccountId"),0)  "CardUPITotal",
coalesce(pr."RegistrationCardGpayTotal",0)+coalesce(ap."AppointmentCardGpayTotal",0)+coalesce(ad."AdmissionCardGpayTotal",0)+coalesce(lb."LabCardGpayTotal",0)+coalesce(sum(pa."PharmaSaleCardGpayTotal") over(partition by a."AccountId"),0)  "CardGpayTotal",
coalesce(pr."RegistrationCashDrawerTotal",0)+coalesce(ap."AppointmentCashDrawerTotal",0)+coalesce(ad."AdmissionCashDrawerTotal",0)+coalesce(lb."LabCashDrawerTotal",0)+coalesce(sum(pa."PharmaSaleCashDrawerTotal") over(partition by a."AccountId"),0)  "CashDrawerTotal",
coalesce(pr."RegistrationCashChequeTotal",0)+coalesce(ap."AppointmentCashChequeTotal",0)+coalesce(ad."AdmissionCashChequeTotal",0)+coalesce(lb."LabCashChequeTotal",0)+coalesce(sum(pa."PharmaSaleCashChequeTotal") over(partition by a."AccountId"),0) "CashChequeTotal",
coalesce(pr."RegistrationCashDDTotal",0)+coalesce(ap."AppointmentCashDDTotal",0)+coalesce(ad."AdmissionCashDDTotal",0)+coalesce(lb."LabCashDDTotal",0)+coalesce(sum(pa."PharmaSaleCashDDTotal") over(partition by a."AccountId"),0)  "CashDDTotal",
coalesce(pr."RegistrationWalletPaytmOfflineTotal",0)+coalesce(ap."AppointmentWalletPaytmOfflineTotal",0)+coalesce(ad."AdmissionWalletPaytmOfflineTotal",0)+coalesce(lb."LabWalletPaytmOfflineTotal",0)+coalesce(sum(pa."PharmaSaleWalletPaytmOfflineTotal")over(partition by a."AccountId"),0)  "WalletPaytmOfflineTotal",
coalesce(ap."AppointmentWalletPhonePeOfflineTotal",0)+coalesce(ap."AppointmentWalletPhonePeOfflineTotal",0)+coalesce(ad."AdmissionWalletPhonePeOfflineTotal",0)+coalesce(lb."LabWalletPhonePeOfflineTotal",0)+coalesce(sum(pa."PharmaSaleWalletPhonePeOfflineTotal") over(partition by a."AccountId"),0)  "WalletPhonePeOfflineTotal",
coalesce(pr."RegistrationCashRemoteDepositTotal",0)+coalesce(ap."AppointmentCashRemoteDepositTotal",0)+	coalesce(ad."AdmissionCashRemoteDepositTotal",0)+coalesce(lb."LabCashRemoteDepositTotal",0)+coalesce(sum(pa."PharmaSaleCashRemoteDepositTotal")over(partition by a."AccountId"),0)  "CashRemoteDepositTotal",
coalesce(pr."RegistrationWalletPaytmDQRTotal",0)+coalesce(ap."AppointmentWalletPaytmDQRTotal",0)+coalesce(ad."AdmissionWalletPaytmDQRTotal",0)+coalesce(lb."LabWalletPaytmDQRTotal",0)+coalesce(sum(pa."PharmaSaleWalletPaytmDQRTotal") over(partition by a."AccountId"),0)  "WalletPaytmDQRTotal",

coalesce(pr."registrationamount",0)+coalesce(ap."AppointmentAmount",0)+coalesce(ad."AdmissionAmount",0)+coalesce(lb."LabAmount",0)
+coalesce(sum(pa."PharmaAmount") over(partition by a."AccountId"),0) "Total"

from accountdata a

left join patientRegistrationamount pr on pr."AccountId"=a."AccountId"
left join appointmentamount ap on ap."AccountId"=a."AccountId"
left join admissionamount ad on ad."AccountId"=a."AccountId"
left join LabAmount lb on lb."AccountId"=a."AccountId"
left join PharmaAmount pa on pa."AccountId"=a."AccountId"
;
	end
$BODY$;

---------------------------------------------------------------------Chandana 01Sep2023----------------------------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_consultation_statistics"(integer, integer, timestamp without time zone, timestamp without time zone);

CREATE OR REPLACE FUNCTION public."udf_consultation_statistics"(
	providerid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone)
    RETURNS TABLE("AccountId" integer, "DoctorName" text, "AppointmentCount" bigint , "AdmissionCount" bigint ,"LabCount" bigint ,  "PharmacyCount" bigint,"ScanCount" bigint ) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
 
begin
 return query 
 with accountdata as (
select a."ProviderId",a."FullName" "DoctorName"
from "Provider" a
JOIN "Account" ac on ac."ReferenceId"=a."ProviderId" and ac."RoleId"=3
JOIN "LocationAccountMap" LAM on LAM."AccountId"=ac."AccountId" 
where case when providerId is null then 1=1 else 
	 a."ProviderId"=providerId end 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE 
	 LAM."LocationId"=locationId END
)


,AppointmentTotal as (	
  select Count(*) as "AppointmentTotal",p."ProviderId",p."FullName" from "Appointment" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId"  and p."Active"<>false
	 where 
		case when providerId is null then 1=1 else ap."ProviderId"=providerId end    
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
		
	and ap."Active"<>false and ap."AppointmentId" is not null  
	 and ap."Status" <> 'C' and	
	case when "fromDate" is null then 1=1 
	else (ap."CreatedDate" >= "fromDate" and ap."CreatedDate" <= "toDate") end
			group by  p."ProviderId"
)
,AdmissionTotal as (
	select Count(*) as "AdmissionTotal",p."ProviderId",p."FullName" from "Admission" ad 
left join "Provider" p on p."ProviderId"=ad."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ad."ProviderId"=providerId end  
		AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and ad."Active"<>false 
	and case when "fromDate" is null then 1=1 
	else (ad."CreatedDate" >= "fromDate" and ad."CreatedDate" <= "toDate")  end
			group by  p."ProviderId"	
	
)
,LabTotal as (select Count(*) as "LabTotal",p."ProviderId",p."FullName" from "NewLabBookingHeader" ar  
left join "Provider" p on p."ProviderId"=ar."DoctorId" and p."Active"<>false
			 
	where case when providerId is null then 1=1 else ar."DoctorId"=providerId end    
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ar."LocationId"=locationId END
	AND case when "fromDate" is null then 1=1 
	else (ar."CreatedDate" >= "fromDate" and ar."CreatedDate" <= "toDate")  end
			group by  p."ProviderId")
			
,PharmaTotal as (select Count(*) as "PharmaTotal",p."ProviderId",p."FullName" from "PharmacySaleHeader" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ap."ProviderId"=providerId end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ap."SaleDate" >= "fromDate" and ap."SaleDate" <= "toDate")  end
			group by  p."ProviderId"	
)	
,ScanTotal as (
	select Count(*) as "ScanTotal",p."ProviderId",p."FullName" from "BookScanAppointment" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ap."ProviderId"=providerId end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ap."CreatedDate" >= "fromDate" and ap."CreatedDate" <= "toDate")  end
			group by  p."ProviderId"
)	
  select distinct  a."ProviderId",a."DoctorName"::text "DoctorName",
						  ap."AppointmentTotal",
						  ad."AdmissionTotal",
						  lb."LabTotal",
						  pa."PharmaTotal",
						  sa."ScanTotal"

from accountdata a
 left join AppointmentTotal ap on ap."ProviderId"=a."ProviderId"
left join AdmissionTotal ad on ad."ProviderId"=a."ProviderId"
left join LabTotal lb on lb."ProviderId"=a."ProviderId"
left join PharmaTotal pa on pa."ProviderId"=a."ProviderId"
left join ScanTotal sa on sa."ProviderId"=a."ProviderId"
;
	end
$BODY$;
-------------------------------------------------------------------------------jayshree 01Sep2023--------------------------------------------------------------
 DROP FUNCTION IF EXISTS public."udf_report_Finance_Billwise"(timestamp without time zone, timestamp without time zone, integer, integer, integer, date, date);

CREATE OR REPLACE FUNCTION public."udf_report_Finance_Billwise"(
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	locationid integer DEFAULT NULL::integer,
	moduleid integer DEFAULT NULL::integer,
	patientid integer DEFAULT NULL::integer,
	"servicefromDate" date DEFAULT NULL::date,
	"servicetoDate" date DEFAULT NULL::date)
    RETURNS TABLE("BillNumber" character varying, "BillDate" timestamp without time zone, "BillStatusTypeId" integer, "BillStatus" character varying, "Total" numeric, "Discount" numeric, "Refund" numeric, "NetTotal" numeric, "Tax" numeric, "Rounding" numeric, "Receipts" text, "Receipts_Cost" text, "ReceiptSum" numeric, "ReceiptAreaTypeId" integer, "PatientName" text, "Mobile" character varying, "UMRNo" character varying, "ProviderName" character varying, "LocationId" integer, "LocationName" character varying, "PatientId" integer, "ModuleName" character varying, "AppointmentNo" character varying, "AppointmentDate" timestamp without time zone, "OPConsultation" numeric, "ScanConsultation" numeric, "Lab" numeric, "Pharmacy" numeric, "RegistrationCharges" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with getreceipts as (
	select  MB."MasterBillId",MB."BillNumber",string_agg(R."ReceiptId"::text,',')   AS "Receipts",
string_agg(R."Cost"::text,',')  AS "Receipts_Cost",MB."ReceiptAreaTypeId",MB."LocationId",L."Name" as "LocationName",
	MB."PatientId",
sum(R."Cost") as "ReceiptSum"
	from "MasterBill" MB 
	 join  "Receipt" R on R."MasterBillId"=MB."MasterBillId"	
	left join "Location" L on L."LocationId"=MB."LocationId"
	join "Patient" P on P."PatientId"=MB."PatientId"
	where R."ReceiptTypeId"=1
		group by (MB."MasterBillId",L."Name")
	--order by MB."BillNumber" asc
)
,patient as(
select 
	distinct on (MB."MasterBillId")
 MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."Refund",MB."NetTotal",MB."Tax",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
AP."FullName" as "PatientName",AP."Mobile",AP."UMRNo",'Doctor'::character varying as "ProviderName",
	MM."Name" as "ModuleName",
AP."UMRNo" as "AppointmentNo",MB."BillDate"::Date as  "AppointmentDate"

FROM "MasterBill" MB
  join "Patient" AP on AP."PatientId"=MB."ModuleId" and MB."ReceiptAreaTypeId"=3
	join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
	 join "AppointmentTransaction" AT on AT."AppointmentId"=AP."PatientId"
	
where-- MB."BillDate"::date=now()::date
case when "servicefromDate" is null then 1=1 else "servicefromDate"<= MB."BillDate"::date end 
 		and case when "servicefromDate" is null then 1=1 else MB."BillDate"::date<=  "servicefromDate" end 
		
)
,appointment as(
select 
	distinct on (MB."MasterBillId")
 MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."Refund",MB."NetTotal",MB."Tax",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",pr."FullName" as "ProviderName",
--AT."LocationId",L."Name" as "LocationName",
	MM."Name" as "ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
FROM "MasterBill" MB
 Join "Appointment" AP on AP."AppointmentId"=MB."ModuleId"
	join "Provider" pr on pr."ProviderId"= AP."ProviderId"
 join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"
 join "Patient" P on P."PatientId"=MB."PatientId"
 --join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"	
join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
 join "AppointmentTransaction" AT on AT."AppointmentId"=AP."AppointmentId"-- and MB."ReceiptAreaTypeId"=4
 --join "Location" L on L."LocationId"=AT."LocationId"	
where  
case when "servicefromDate" is null then 1=1 else "servicefromDate"<= AP."AppointmentDate"::date end 
 		and case when "servicetoDate" is null then 1=1 else AP."AppointmentDate"::date<=  "servicetoDate"::date end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end
)
,lab as (
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."Refund",MB."NetTotal",MB."Tax",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",prv."FullName" as "ProviderName",
--	L."Name" as "LocationName",nlbh."LocationId",
	MM."Name" as "ModuleName",
 nlbh."RequisitionNumber" as "AppointmentNo",nlbh."CreatedDate" as "AppointmentDate"
FROM "MasterBill" MB
			join "NewLabBookingHeader" nlbh on nlbh."NewLabBookingHeaderId"=MB."ModuleId"
			join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"    
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"   
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."NewLabBookingHeaderId"
		   -- join "Location" L on L."LocationId"=AT."LocationId"
		where 	
	case when "servicefromDate" is null then 1=1 else "servicefromDate"<= nlbh."CreatedDate"::date end 
 		and case when "servicetoDate" is null then 1=1 else nlbh."CreatedDate"::date<=  "servicetoDate" end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end																		  								   
)
,pharma as (
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."Refund",MB."NetTotal",MB."Tax",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",nlbh."ProviderName",
	--L."Name" as "LocationName",nlbh."LocationId",
	MM."Name" as "ModuleName",
 nlbh."BillNumber" as "AppointmentNo",nlbh."CreatedDate" as "AppointmentDate"		
	FROM "MasterBill" MB
			join "PharmacySaleHeader" nlbh on nlbh."PharmacySaleHeaderId"=MB."ModuleId"                               
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId" 
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."PharmacySaleHeaderId"
			--join "Location" L on L."LocationId"=AT."LocationId"
	where 
		case when "servicefromDate" is null then 1=1 else "servicefromDate"<= nlbh."CreatedDate"::date end 
 		and case when "servicetoDate" is null then 1=1 else nlbh."CreatedDate"::date<=  "servicetoDate" end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end																		  								   
)
,scan as(
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."Refund",MB."NetTotal",MB."Tax",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",SM."MachineName" as "ProviderName",
	--L."Name" as "LocationName",nlbh."LocationId",
	MM."Name" as "ModuleName",
 nlbh."RequisitionNumber" as "AppointmentNo",nlbh."AppointmentDate"			
	FROM "MasterBill" MB
			join "BookScanAppointment" nlbh on nlbh."BookScanAppointmentId"=MB."ModuleId" 
			join "ScanMachineMaster" SM on SM."ScanMachineMasterId"=nlbh."ScanMachineMasterId"
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"  
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."BookScanAppointmentId"
		    --join "Location" L on L."LocationId"=AT."LocationId"
	where
		case when "servicefromDate" is null then 1=1 else "servicefromDate"<= nlbh."AppointmentDate"::date end 
 		and case when "servicetoDate" is null then 1=1 else nlbh."AppointmentDate"::date<=  "servicetoDate" end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end	
)

SELECT O."BillNumber",O."BillDate",O."BillStatusTypeId",O."BillStatus",
O."Total",O."Discount",O."Refund",O."NetTotal",O."Tax",O."Rounding",O."Receipts",O."Receipts_Cost",O."ReceiptSum",O."ReceiptAreaTypeId",
O."PatientName",O."Mobile",O."UMRNo",O."ProviderName",
O."LocationId",O."LocationName",O."PatientId",
O."ModuleName",
O."AppointmentNo",O."AppointmentDate",
coalesce(case when O."ReceiptAreaTypeId"=4 then O."ReceiptSum" end,0) as "OPConsultation" ,
coalesce(case when O."ReceiptAreaTypeId"=10 then O."ReceiptSum" end,0) as "ScanConsultation",
coalesce(case when O."ReceiptAreaTypeId"=8 then O."ReceiptSum" end,0) as "Lab" ,
coalesce(case when O."ReceiptAreaTypeId"=1 then O."ReceiptSum" end,0) as "Pharmacy",
coalesce(case when O."ReceiptAreaTypeId"=3 then O."ReceiptSum" end,0) as "RegistrationCharges"
from 
(
	
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."Refund",AP."NetTotal",AP."Tax",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "patient" AP on GR."MasterBillId"=AP."MasterBillId"	
UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."Refund",AP."NetTotal",AP."Tax",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "appointment" AP on GR."MasterBillId"=AP."MasterBillId"	
UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."Refund",AP."NetTotal",AP."Tax",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "lab" AP on GR."MasterBillId"=AP."MasterBillId"
	
	UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."Refund",AP."NetTotal",AP."Tax",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "pharma" AP on GR."MasterBillId"=AP."MasterBillId"
	UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."Refund",AP."NetTotal",AP."Tax",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "scan" AP on GR."MasterBillId"=AP."MasterBillId"
		
)O
where 	
	 case when "moduleid" is null then 1=1 else O."ReceiptAreaTypeId" = "moduleid" end	
	 and case when "locationid" is null then 1=1 else O."LocationId" = "locationid" end	
	 and case when "patientid" is null then 1=1 else O."PatientId" = "patientid" end	
	 
	 and case when "fromDate" is null then 1=1 else "fromDate"<= O."BillDate" end 
 		and case when "toDate" is null then 1=1 else O."BillDate"<=  "toDate" end 
		
	 
GROUP BY GROUPING SETS((O."BillNumber",O."BillDate",O."BillStatusTypeId",O."BillStatus",
O."Total",O."Discount",O."Refund",O."NetTotal",O."Tax",O."Rounding",O."Receipts",O."Receipts_Cost",O."ReceiptSum",O."ReceiptAreaTypeId",
O."PatientName",O."Mobile",O."UMRNo",O."ProviderName",
O."LocationId",O."ModuleName",O."LocationName",O."PatientId",
O."AppointmentNo",O."AppointmentDate")) 

order by O."ModuleName" asc;

end
$BODY$;

-----------------------------------------------------------------------Sandeep 03Sep2023-------------------------------------------------------------------------------
ALTER TABLE if exists public."AdmissionPackage"
    ADD COLUMN if not exists "CounsellingId" integer;

-----------------------------------------------------------------------Radhika 04Sep2023-------------------------------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_fetch_LabOrderDetails"(integer, text, timestamp without time zone, timestamp without time zone, integer, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_fetch_LabOrderDetails"(
	"patientId" integer DEFAULT NULL::integer,
	"uMRNo" text DEFAULT NULL::text,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"doctorId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer,
	"labMainDetailId" integer DEFAULT NULL::integer)
    RETURNS TABLE("TotalItems" bigint, "newLabBookingHeaderId" integer, "createdDate" timestamp without time zone, "DoctorName" character varying, "PatientName" character varying, "UMRNo" character varying, "Status" text, "labBookingStatusId" integer, "LabMainDetailId" integer, "TestName" text, "StatusDate" timestamp without time zone, "ApprovedDate" timestamp without time zone) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
Declare 
BEGIN
return query

 with statusDate as (
                        select distinct "NewLabBookingHeaderId" as nl,"LabBookingStatusId" as lb,max("CreatedDate") as "StatusDate"
                        from "LabBookingTimeLine"	                       
	 where case when  "fromDate" is null then 1=1 else  "fromDate"::date <= "CreatedDate"::date and "CreatedDate"::date <= "toDate"::date end
	  group by  "NewLabBookingHeaderId","LabBookingStatusId"
                        )

SELECT count(nlbh.*) over () as "TotalItems",
                        nlbh."NewLabBookingHeaderId" as newLabBookingHeaderId, 
             nlbh."CreatedDate", prv."FullName"  as "DoctorName" ,
           nlbh."PatientName" , p."UMRNo",LS."Status", LS."LabBookingStatusId" as labBookingStatusId,
		   LN."LabMainDetailId",
		   LN."TestName",T."StatusDate",lrv."ApprovedDate"                                       
            							
                                    from "NewLabBookingHeader" nlbh
                                    join "NewLabBookingDetail" LBD on nlbh."NewLabBookingHeaderId"=LBD."NewLabBookingHeaderId"  and nlbh."Active"<> false
                                    join "LabMainDetail" LN on LN."LabMainDetailId" = LBD."LabMainDetailId"
                                    join "LabDepartment" LD  on LD."LabDepartmentId"=LN."LabDepartmentId"
                                    join "LabBookingStatus" LS on LS."LabBookingStatusId" = LBD."LabBookingStatusId"
                                    join "Account" c on c."AccountId" = nlbh."CreatedBy" 
                                    join "Location" l ON l."LocationId" = nlbh."LocationId"
                                    left join "Patient" p ON p."PatientId" =nlbh."PatientId"
                                    left join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"
                                    left join "Department" PD on PD."DepartmentId"=prv."DepartmentId"
                                    left join statusDate T on T."nl"=nlbh."NewLabBookingHeaderId" and T."lb"=LBD."LabBookingStatusId"
                         			left join "LabReportVerification" lrv on lrv."NewLabBookingDetailId"=LBD."NewLabBookingDetailId"
where case when "uMRNo" ='' then 1=1   when "uMRNo" is null then 1=1  else p."UMRNo" ilike  '%'||"uMRNo"||'%' end and 
case when "doctorId" is null then 1=1 else nlbh."DoctorId"="doctorId" end and
	case when "labMainDetailId" is null then 1=1 else LBD."LabMainDetailId"="labMainDetailId" end and
	case when "patientId" is null then 1=1 else P."PatientId"="patientId" end and
 case when "fromDate" is null then 1=1 else  "fromDate"::date <= nlbh."CreatedDate"::date and nlbh."CreatedDate"::date <= "toDate"::date end
and case when "locationId" is null then 1=1 else nlbh."LocationId" = "locationId"::int end

;

END
$BODY$;
----------------------------------------------------------------------Chandana 5Sep2023----------------------------------------------------------------------------

DROP FUNCTION IF EXISTS public."udf_report_TransactionTallyExcel"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_report_TransactionTallyExcel"(
	"fromDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	locationid integer DEFAULT NULL::integer,
	moduleid integer DEFAULT NULL::integer)
    RETURNS TABLE("TotalItems" bigint, "TransactionDate" timestamp without time zone, "TransactionId" character varying, "VoucherNumber" character varying, "SendedVia" text, "ReceivedIn" text, "PayStatus" character, "ReceiptTypeName" character varying, "ReceiptAreaType" character varying, "AreaId" integer, "Cost" numeric, "ReceiptId" integer, "AppAmount" numeric, "AppDiscount" numeric, "AppTotal" numeric, "UMRNo" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

 with discountData as(
	 --patient 
        SELECT A."Amount",A."DiscountInRupees" "Discount",A."Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "Patient" A on A."PatientId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 3 and A."DiscountInRupees" > 0
	 			 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 				and case when "toDate" is null then 1=1 else  AT."CreatedDate"<=  "toDate" end 
	 UNION ALL
	--appointment
        SELECT A."Amount",A."Discount",A."Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "Appointment" A on A."AppointmentId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 4 and A."Discount" > 0
	 			 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 				and case when "toDate" is null then 1=1 else  AT."CreatedDate"<=  "toDate" end 
  
UNION ALL
	--scan
        SELECT A."ActualAmount" "Amount",A."DiscountAmount" "Discount",A."Amount" "Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "BookScanAppointment" A on A."BookScanAppointmentId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 10 and A."DiscountAmount" > 0
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  AT."CreatedDate"<=  "toDate" end 
UNION ALL
	--lab
        SELECT A."OverallTotalAmount" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "NewLabBookingHeader" A on A."NewLabBookingHeaderId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 8 and A."OverallDiscount" > 0 
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  AT."CreatedDate" <=  "toDate" end 
UNION ALL
--pharma	
        SELECT A."Total" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "PharmacySaleHeader" A on A."PharmacySaleHeaderId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 1 and A."OverallDiscount" > 0 
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  AT."CreatedDate" <=  "toDate" end 
union all
--admission	 
	 SELECT A."TotalAmount" "Amount",A."DiscountDetails" "Discount",A."FinalAmount" "Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
           join "FinalBill" A on A."AdmissionId" = R."AdmissionId"
           join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 12 and A."DiscountDetails" > 0 
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  AT."CreatedDate" <=  "toDate" end
			
 )
   SELECT  COUNT(*) OVER () AS "TotalItems" ,T."TransactionDate",T."TransactionId",T."VoucherNumber",
   		T."SendedVia",T."ReceivedIn",T."PayStatus"
    ,RT."ReceiptTypeName",RA."Name" as "ReceiptAreaType",RA."ReceiptAreaTypeId" as "AreaId",
	--PM."PaymentType",
	R."Cost",R."ReceiptId"
    ,DD."Amount"  as "AppAmount",DD."Discount" as "AppDiscount",DD."Total" as "AppTotal" 
	 ,P."UMRNo"
 	from "AppointmentTransaction"  T
	left Join "ReceiptType" RT on RT."ReceiptTypeId"=T."ReceiptTypeId" 
	left Join "ReceiptAreaType" RA on   RA."ReceiptAreaTypeId"=T."ReceiptAreaTypeId"
 	left join "PaymentMode" PM on PM."PaymentModeId"=T."PaymentModeId"
 	Join "Receipt" R on R."TransactionId"=T."AppointmentTransactionId"
	left join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
	left join "Patient" P on P."PatientId"=MB."PatientId"
 	--left join appDiscountData  AD on AD."AppointmentTransactionId"=T."AppointmentTransactionId"
	left join discountData  DD on DD."AppointmentTransactionId"=T."AppointmentTransactionId"
   where 
   	case when "moduleid" is null then 1=1 else RA."ReceiptAreaTypeId" = "moduleid" end	
	 and case when "locationid" is null then 1=1 else T."LocationId" = "locationid" end		 
	 and case when "fromDate" is null then 1=1 else "fromDate"<=  T."CreatedDate" end 
 	and case when "toDate" is null then 1=1 else  T."CreatedDate" <=  "toDate" end 

	order by T."TransactionDate" desc 
;

end
$BODY$;


DROP FUNCTION IF EXISTS public."udf_consultation_statistics"(integer, integer, timestamp without time zone, timestamp without time zone);

CREATE OR REPLACE FUNCTION public."udf_consultation_statistics"(
	providerid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone)
    RETURNS TABLE("AccountId" integer, "DoctorName" text, "AppointmentCount" bigint , "AdmissionCount" bigint ,"LabCount" bigint ,  "PharmacyCount" bigint,"ScanCount" bigint ) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
 
begin
 return query 
 with accountdata as (
select a."ProviderId",a."FullName" "DoctorName"
from "Provider" a
JOIN "Account" ac on ac."ReferenceId"=a."ProviderId" and ac."RoleId"=3
JOIN "LocationAccountMap" LAM on LAM."AccountId"=ac."AccountId" 
where case when providerId is null then 1=1 else 
	 a."ProviderId"=providerId end 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE 
	 LAM."LocationId"=locationId END
)


,AppointmentTotal as (	
  select Count(*) as "AppointmentTotal",p."ProviderId",p."FullName" from "Appointment" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId"  and p."Active"<>false
	 where 
		case when providerId is null then 1=1 else ap."ProviderId"=providerId end    
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
		
	and ap."Active"<>false and ap."AppointmentId" is not null  
	 and ap."Status" <> 'C' and	
	case when "fromDate" is null then 1=1 
	else (ap."CreatedDate" >= "fromDate" and ap."CreatedDate" <= "toDate") end
			group by  p."ProviderId"
)
,AdmissionTotal as (
	select Count(*) as "AdmissionTotal",p."ProviderId",p."FullName" from "Admission" ad 
left join "Provider" p on p."ProviderId"=ad."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ad."ProviderId"=providerId end  
		AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and ad."Active"<>false 
	and case when "fromDate" is null then 1=1 
	else (ad."CreatedDate" >= "fromDate" and ad."CreatedDate" <= "toDate")  end
			group by  p."ProviderId"	
	
)
,LabTotal as (select Count(*) as "LabTotal",p."ProviderId",p."FullName" from "NewLabBookingHeader" ar  
left join "Provider" p on p."ProviderId"=ar."DoctorId" and p."Active"<>false
			 
	where case when providerId is null then 1=1 else ar."DoctorId"=providerId end    
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ar."LocationId"=locationId END
	and ar."Active" <> false
			  AND case when "fromDate" is null then 1=1 
	else (ar."CreatedDate" >= "fromDate" and ar."CreatedDate" <= "toDate")  end
			group by  p."ProviderId")
			
,PharmaTotal as (select Count(*) as "PharmaTotal",p."ProviderId",p."FullName" from "PharmacySaleHeader" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ap."ProviderId"=providerId end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ap."SaleDate" >= "fromDate" and ap."SaleDate" <= "toDate")  end
			group by  p."ProviderId"	
)	
,ScanTotal as (
	select Count(*) as "ScanTotal",p."ProviderId",p."FullName" from "BookScanAppointment" ap 
left join "Provider" p on p."ProviderId"=ap."ProviderId" and p."Active"<>false
	where case when providerId is null then 1=1 else ap."ProviderId"=providerId end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END
	and ap."Status" <> 'C'
	and case when "fromDate" is null then 1=1 
else (ap."CreatedDate" >= "fromDate" and ap."CreatedDate" <= "toDate")  end
			group by  p."ProviderId"
)	
  select distinct  a."ProviderId",a."DoctorName"::text "DoctorName",
						  ap."AppointmentTotal",
						  ad."AdmissionTotal",
						  lb."LabTotal",
						  pa."PharmaTotal",
						  sa."ScanTotal"

from accountdata a
 left join AppointmentTotal ap on ap."ProviderId"=a."ProviderId"
left join AdmissionTotal ad on ad."ProviderId"=a."ProviderId"
left join LabTotal lb on lb."ProviderId"=a."ProviderId"
left join PharmaTotal pa on pa."ProviderId"=a."ProviderId"
left join ScanTotal sa on sa."ProviderId"=a."ProviderId"
;
	end
$BODY$;

------------------------------------------------------------Chandana 07Sep2023--------------------------------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_report_BillDiscount"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_report_BillDiscount"(
	"fromDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	locationid integer DEFAULT NULL::integer,
	moduleid integer DEFAULT NULL::integer)
    RETURNS TABLE("TotalItems" bigint, "PatientName" text, "Cost" numeric, "UMRNo" character varying, "ReceiptAreaTypeId" integer, "Type" character varying, "Discount" numeric, "Total" numeric, "CreatedBy" integer, "createdDate" timestamp without time zone, "BilledBy" text,"LocationId" int,"LocationName" character varying(255)) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

 with discountData as(
	 --patient 
        SELECT A."LocationId",A."FullName",A."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."Amount",A."DiscountInRupees" "Discount",A."Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "Patient" A
         join "Receipt" r on r."RespectiveId"=A."PatientId" and r."ReceiptAreaTypeId" =3
	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where A."DiscountInRupees" >= 0
	 			 and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 				and case when "toDate" is null then 1=1 else  A."CreatedDate"<=  "toDate" end 
	 UNION ALL
	--appointment
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."Amount",A."Discount",A."Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "Appointment" A
	  join "Patient" p on p."PatientId" = A."PatientId"	 
	join "Receipt" r on r."RespectiveId"=A."AppointmentId" and r."ReceiptAreaTypeId" =4
	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where A."PaymentStatus"<>False and A."Active"<>false and  A."Status" <> 'C' and A."Discount" >= 0
	 			 and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 				and case when "toDate" is null then 1=1 else  A."CreatedDate"<=  "toDate" end 
  
UNION ALL
	--scan
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."ActualAmount" "Amount",A."DiscountAmount" "Discount",A."Amount" "Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "BookScanAppointment" A
	 join "Patient" p on p."PatientId" = A."PatientId"
	 join "Receipt" r on r."RespectiveId"=A."BookScanAppointmentId" and r."ReceiptAreaTypeId" =10
	 	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where  A."Status" <> 'C' and A."DiscountAmount" >= 0
	 		and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  A."CreatedDate"<=  "toDate" end 
UNION ALL
	--lab
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."OverallTotalAmount" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "NewLabBookingHeader" A
          join "Patient" p on p."PatientId" = A."PatientId"
	 join "Receipt" r on r."RespectiveId"=A."NewLabBookingHeaderId" and r."ReceiptAreaTypeId" =8
	 	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where  A."Active" <> false and A."OverallDiscount" >= 0 
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  A."CreatedDate" <=  "toDate" end 
UNION ALL
--pharma	
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."Total" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "PharmacySaleHeader" A
           join "Patient" p on p."PatientId" = A."PatientId"
	  join "Receipt" r on r."RespectiveId"=A."PharmacySaleHeaderId" and r."ReceiptAreaTypeId" =1
	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where A."OverallDiscount" >= 0 
	 		and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  A."CreatedDate" <=  "toDate" end 
 )
 select count(*) over() as  "TotalItems",d."FullName" , d."Amount",d."UMRNo",d."ReceiptAreaTypeId",d."Type",d."Discount",d."Total",d."CreatedBy",d."CreatedDate",d."BilledBy",d."LocationId",l."Name" as "LocationName"  from discountData d
   join "Location" l on l."LocationId" =d."LocationId"
   where 
   	case when "moduleid" is null then 1=1 else d."ReceiptAreaTypeId" = "moduleid" end
and 	case when "locationid" is null then 1=1 else d."LocationId" = locationid end
	and case when "fromDate" is null then 1=1 else "fromDate"<=  d."CreatedDate" end 
 	and case when "toDate" is null then 1=1 else  d."CreatedDate" <=  "toDate" end 

;
	
end
$BODY$;
---------------------------------------------------------Radhika 07Sep2023-------------------------------------------------------------------------------------






DROP FUNCTION IF EXISTS public."widget_BarChart_Lab_Revenue1"(date, text, integer, integer, integer);

CREATE OR REPLACE FUNCTION public."widget_BarChart_Lab_Revenue1"(
	"fromDate" date,
	"filterType" text,
	"displayCount" integer,
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
filtervalue interval;
intervaldata interval;
fromdate date;
begin
create  Temp TABLE temp_table 
( labdate date,
  labamount numeric
 ) ON COMMIT DELETE ROWS;
 filtervalue=  "displayCount"||' '|| "filterType";
 intervaldata= '1 '|| "filterType";
 raise notice ' %', filtervalue;
 --fromdate:=case when "filterType"='day' then "fromDate" 
 --else date_trunc('month', "fromDate"::date) end;
for f in SELECT generate_series("fromDate" -  filtervalue , "fromDate" +   filtervalue,  intervaldata) weeks
    loop 
	
	insert into temp_table (labdate,labamount)
	
	select f.weeks,coalesce(sum(coalesce(ar."OverallNetAmount",0)),0) "LabAmount" 
from "NewLabBookingHeader" ar
left join "Provider" pr on pr."ProviderId"= ar."DoctorId"
left join "ProviderLocation" PL on PL."ProviderId"=pr."ProviderId" and case when "locationId" is null then 1=1 else  PL."LocationId"= "locationId" end
left join "Account" PA on PA."ReferenceId"=pr."ProviderId"  and PA."RoleId"=3
where ar."Active" <> false and (ar."CreatedDate"::date >= f.weeks::text::date and ar."CreatedDate"::date < (f.weeks+ intervaldata)::text::date)
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
and case when ("referenceId" is null) or ("referenceId"=0) then 1=1 else PA."ReferenceId"= "referenceId" end
;
	
	
	
   
    end loop;
	RETURN QUERY
	select A.labdate,A.labamount from temp_table A;
	drop table temp_table;
END;
$BODY$;

 DROP FUNCTION IF EXISTS public."widget_PieChart_Lab_Revenue1"(date, text, integer, integer);

CREATE OR REPLACE FUNCTION public."widget_PieChart_Lab_Revenue1"(
	"fromDate" date,
	"filterType" text,
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
intervaldata interval;
ftype text;
currentdate date;
fromdate date;
begin
intervaldata:= case when "filterType"='day' then '1 D' when "filterType"='month' then '1 Month' when "filterType"='year' then '1 Year' end;
ftype:= case when "filterType"='day' then 'month'::text  when "filterType"='month' then 'year'::text when "filterType"='year' then 'year'::text end;
currentdate:= case when  "filterType"='year' then date_trunc(ftype, "fromDate")  - '2 Y'::interval else date_trunc(ftype, "fromDate") end ;
fromdate:=case when "filterType"='day' and  current_date > "fromDate"  then   (date_trunc('month', "fromDate"::date) + interval '1 month' - interval '1 day')::date
 when  "filterType"='month' and   "fromDate" < current_date then  date_trunc('Year', "fromDate"::date) + interval '1 Year' - interval '1 month' 
 
else "fromDate" end;

 raise notice 'intervaldata %', intervaldata;
 raise notice 'ftype %', ftype;
  raise notice 'currentdate %', currentdate;
create  Temp TABLE temp_table 
( startdate date,
   enddate date,  
  countdata numeric
 ) ON COMMIT DELETE ROWS;
 
for f in 
 select   generate_series( currentdate  , fromdate,  intervaldata)  weeks 
    loop 
	raise notice 'currentdate %', f.weeks::text::date;
	raise notice 'fromdate %', fromdate::date;
	insert into temp_table (startdate,enddate,countdata)
	
	select date_trunc('month', current_date)::date startdate ,f.weeks enddate,coalesce(sum(coalesce(ar."OverallNetAmount",0)),0) "LabAmount" 
from "NewLabBookingHeader" ar 
left join "Provider" pr on pr."ProviderId"= ar."DoctorId"
left join "ProviderLocation" PL on PL."ProviderId"=pr."ProviderId" and case when "locationId" is null then 1=1 else  PL."LocationId"= "locationId" end

left join "Account" PA on PA."ReferenceId"=pr."ProviderId"  and PA."RoleId"=3
where ar."Active" <> false and (ar."CreatedDate"::date >= f.weeks::text::date and ar."CreatedDate"::date < (f.weeks+ intervaldata)::text::date)
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
and case when ("referenceId" is null) or ("referenceId"=0) then 1=1 else PA."ReferenceId"= "referenceId" end
;	
   
    end loop;
	RETURN QUERY
	select A.enddate,A.countdata from temp_table A;
	drop table temp_table;
END;
$BODY$;
----------------------------------------------------------------Mahesh 7Sep2023--------------------------------------------------------------------------
INSERT INTO public."LogType"("LogTypeId","LogTypeName","Active")
SELECT 97,'Tpa',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LogType" WHERE "LogTypeName" = 'Tpa'
);
--------------------------------------------------------------------Radhika 07Sep2023--------------------------------------------------------------------------





DROP FUNCTION IF EXISTS public."widget_Chart_Lab_Revenue1"(text, date, text, integer, integer, integer);

CREATE OR REPLACE FUNCTION public."widget_Chart_Lab_Revenue1"(
	"chartType" text,
	"fromDate" date,
	"filterType" text,
	"displayCount" integer DEFAULT NULL::integer,	
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer
	)
    RETURNS TABLE("Date" date, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
DECLARE
sql text := 'select "Date", "Count"::numeric from ';
BEGIN
   IF "chartType"='Bar' THEN
      sql := sql || '"widget_BarChart_Lab_Revenue1"('''||"fromDate"||''','''||"filterType"||''', '''||"displayCount"||''','''||coalesce("referenceId",0)||''','''||coalesce("locationId",0)||''')';
   ELSE 
     sql := sql || '"widget_PieChart_Lab_Revenue1"('''||"fromDate"||''','''||"filterType"||''','''||coalesce("referenceId",0)||''','''||coalesce("locationId",0)||''')';
    
   END IF;
   raise notice 'query %', sql;
   RETURN QUERY EXECUTE sql;
END
$BODY$;

 DROP FUNCTION IF EXISTS public."widget_BarChart_OverAllRevenue1"(date, text, integer, integer);

CREATE OR REPLACE FUNCTION public."widget_BarChart_OverAllRevenue1"(
	"fromDate" date,
	"filterType" text,
	"displayCount" integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Name" text, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
filtervalue interval;
intervaldata interval;
fromdate date;

begin
create  Temp TABLE temp_table 
( ddate date, 
  dname text,
  countdata numeric
 ) ON COMMIT DELETE ROWS;
 filtervalue=  "displayCount"||' '|| "filterType";
 intervaldata= '1 '|| "filterType";

raise notice 'filtervalue %', filtervalue;

--fromdate:=case when "filterType"='day' then "fromDate" 
 --else date_trunc('month', "fromDate"::date) end;

for f in SELECT generate_series("fromDate"-filtervalue, "fromDate"+filtervalue,  intervaldata) weeks
    loop 
	raise notice 'fromdate %', "fromDate"-filtervalue;
	raise notice 'todate %', "fromDate"+filtervalue;
	insert into temp_table (ddate,dname,countdata)

with actappointmentamount as (
	
	select  A.appointmentamount::bigint appointmentamount from (
   select    sum(coalesce(AP."Total",0)) appointmentamount
		
from "Appointment" ap
   where ap."Status" <> 'C' 
	and	(Ap."AppointmentDate" >= f.weeks::text::date and Ap."AppointmentDate" < (f.weeks+ intervaldata)::text::date)
	and case when ("locationId" is null) or ("locationId"=0) then 1=1 else AP."LocationId"= "locationId" end
	  	)a
)

,appointmentamount as (
select 
	
	coalesce(A.appointmentamount,0) as "AppointmentAmount" from actappointmentamount A 
)
,actadmissionamount as (
	
	select  a."Total" "AdmissionAmount" from (
select sum(coalesce(adr."Cost",0)) "Total"									  
												  
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where  	
	 adr."ReceiptTypeId"=1  and adr."Active"<>false  and adr."AdmissionId" is not null
		and adr."CreatedDate"::date >= f.weeks::text::date and adr."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date
		and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ad."LocationId"= "locationId" end
	)a
	
)

,refadmissionamount as (
	select  a."Total" "AdmissionRefAmount" from (
select sum(coalesce(adr."Cost",0)) "Total" 
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where 
	  adr."IsRefunded" = true   and adr."Active"<>false  and adr."AdmissionId" is not null
		and adr."CreatedDate"::date >= f.weeks::text::date and adr."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date
	and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ad."LocationId"= "locationId" end	
	
	)a
	
)
,admissionamount as (
select 
	coalesce(A."AdmissionAmount",0) - coalesce(B."AdmissionRefAmount",0) "AdmissionAmount"
   from actadmissionamount A ,refadmissionamount B 
	

)

,LabAmount as ( 
select a."TotalAmount" "LabAmount" from(
	select sum(coalesce(ar."OverallNetAmount",0)) "TotalAmount"
from "NewLabBookingHeader" ar
where ar."Active" <> false and (ar."CreatedDate"::date >= f.weeks::text::date and ar."CreatedDate"::date < (f.weeks+ intervaldata)::text::date)	
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
	)a
)

,PharmaSaleAmount as (
	
select a."Total"
	"PharmaSaleAmount" from (
select sum(coalesce(ar."OverallNetAmount",0)) "Total"
from "PharmacySaleHeader" ar
where ar."SaleDate"::date >= f.weeks::text::date and ar."SaleDate"::date <= (f.weeks+ intervaldata)::text::date	
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
	
	)a

)
,PharmaReturnAmount as (
select a."Total" "PharmaReturnAmount" from(
select sum(coalesce(ar."OverallNetAmount",0)) "Total"
from "SaleReturnHeader" ar
left join "PharmacySaleHeader" srh on srh."PharmacySaleHeaderId" = ar."PharmacySaleHeaderId"
 where ar."ReturnDate" ::date >= f.weeks::text::date and ar."ReturnDate" ::date <= (f.weeks+ intervaldata)::text::date	
)a

)

,PharmaAmount as (
select 

	coalesce(a."PharmaSaleAmount",0) - coalesce(b. "PharmaReturnAmount",0) as  "PharmaAmount" 
from PharmaSaleAmount a ,PharmaReturnAmount b 
	

)
,finaldata as (select 
case when "Total" = 0 then 0 else round("AppointmentAmount"/"Total"*100,2) end "AppointmentAmount",
case when "Total" = 0 then 0 else round("AdmissionAmount"/"Total"*100,2) end "AdmissionAmount",
case when "Total" = 0 then 0 else round("LabAmount"/"Total"*100,2) end "LabAmount", 
case when "Total" = 0 then 0 else round("PharmacyAmount"/"Total"*100,2) end "PharmacyAmount",
"Total" 
from (
select distinct 
	ap."AppointmentAmount",
	ad."AdmissionAmount",
	lb."LabAmount",
sum(pa."PharmaAmount") over() "PharmacyAmount",	
coalesce(ap."AppointmentAmount",0)+coalesce(ad."AdmissionAmount",0)+coalesce(lb."LabAmount",0)
+coalesce(sum(pa."PharmaAmount") over(),0) "Total"

from  appointmentamount ap , admissionamount ad ,LabAmount lb ,PharmaAmount pa ) a)

select f.weeks,
       unnest(array['AppointmentAmount','AdmissionAmount','LabAmount', 'PharmacyAmount']) as "Name",
       unnest(array[ coalesce("AppointmentAmount",0),coalesce("AdmissionAmount",0),coalesce("LabAmount",0), coalesce("PharmacyAmount",0)]) as "Count" 
from finaldata;
end loop;
	RETURN QUERY
	
	select A.ddate,A.dname,A.countdata from temp_table A;
	drop table temp_table;
	--drop table temp_date_table;				
	
END;
$BODY$;

---------------------------------------------------------------------------------------------------
 DROP FUNCTION IF EXISTS public."widget_PieChart_OverAllRevenue1"(date, text, integer);

CREATE OR REPLACE FUNCTION public."widget_PieChart_OverAllRevenue1"(
	"fromDate" date,
	"filterType" text,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Name" text, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
intervaldata interval;
ftype text;
currentdate date;
fromdate date;
begin
intervaldata:= case when "filterType"='day' then '1 D' when "filterType"='month' then '1 Month' when "filterType"='year' then '1 Year' end;
ftype:= case when "filterType"='day' then 'month'::text  when "filterType"='month' then 'year'::text when "filterType"='year' then 'year'::text end;
currentdate:= case when  "filterType"='year' then date_trunc(ftype, "fromDate")  - '2 Y'::interval else date_trunc(ftype, "fromDate") end ;
fromdate:=case when "filterType"='day' and  current_date > "fromDate"  then   (date_trunc('month', "fromDate"::date) + interval '1 month' - interval '1 day')::date
 when  "filterType"='month' and   "fromDate" < current_date then  date_trunc('Year', "fromDate"::date) + interval '1 Year' - interval '1 month' 
 
else "fromDate" end;

 raise notice 'intervaldata %', intervaldata;
 raise notice 'ftype %', ftype;
  raise notice 'currentdate %', currentdate;
create  Temp TABLE temp_table 
(
	startdate date,
   	enddate date, 
	dname text,
  	countdata numeric
 ) ON COMMIT DELETE ROWS;
 
create  Temp TABLE temp_date_table 
( startdate date,
   enddate date
 ) ON COMMIT DELETE ROWS;
 for f in 
 select   generate_series( currentdate  , fromdate,  intervaldata)  weeks 
    loop 
           insert into temp_date_table (startdate,enddate)
		   select f.weeks::text::date ,(f.weeks+ intervaldata)::text::date ;
		   --raise notice 'datetable %', f.weeks::text::date;
   end loop;
for f in 
 select   generate_series( currentdate  , fromdate,  intervaldata)  weeks 
    loop 
	raise notice 'currentdate %', f.weeks::text::date;
	raise notice 'fromdate %', fromdate::date;
	insert into temp_table (startdate,enddate,dname,countdata)

with actappointmentamount as (
	
	select  A.appointmentamount::bigint appointmentamount from (
   select    sum(coalesce(AP."Total",0)) appointmentamount
		
from "Appointment" ap
   where ap."Status" <> 'C' 
	and	(Ap."AppointmentDate" >= f.weeks::text::date and Ap."AppointmentDate" < (f.weeks+ intervaldata)::text::date)
	and case when ("locationId" is null) or ("locationId"=0) then 1=1 else AP."LocationId"= "locationId" end
	  	)a
)

,appointmentamount as (
select 
	
	coalesce(A.appointmentamount,0) as "AppointmentAmount" from actappointmentamount A 
)
,actadmissionamount as (
	
	select  a."Total" "AdmissionAmount" from (
select sum(coalesce(adr."Cost",0)) "Total"									  
												  
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where  	
	 adr."ReceiptTypeId"=1  and adr."Active"<>false  and adr."AdmissionId" is not null
		and adr."CreatedDate"::date >= f.weeks::text::date and adr."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date	
		and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ad."LocationId"= "locationId" end
	)a
	
)

,refadmissionamount as (
	select  a."Total" "AdmissionRefAmount" from (
select sum(coalesce(adr."Cost",0)) "Total" 
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where 
	  adr."IsRefunded" = true   and adr."Active"<>false  and adr."AdmissionId" is not null
		and adr."CreatedDate"::date >= f.weeks::text::date and adr."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date	
	and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ad."LocationId"= "locationId" end	
	
	)a
	
)
,admissionamount as (
select 
	coalesce(A."AdmissionAmount",0) - coalesce(B."AdmissionRefAmount",0) "AdmissionAmount"
   from actadmissionamount A ,refadmissionamount B 
	

)

,LabAmount as ( 
select a."TotalAmount" "LabAmount" from(
	select sum(coalesce(ar."OverallNetAmount",0)) "TotalAmount"
from "NewLabBookingHeader" ar
where ar."Active" <> false and (ar."CreatedDate"::date >= f.weeks::text::date and ar."CreatedDate"::date < (f.weeks+ intervaldata)::text::date)	
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
	)a
)

,PharmaSaleAmount as (
	
select a."Total"
	"PharmaSaleAmount" from (
select sum(coalesce(ar."OverallNetAmount",0)) "Total"
from "PharmacySaleHeader" ar
where ar."SaleDate"::date >= f.weeks::text::date and ar."SaleDate"::date <= (f.weeks+ intervaldata)::text::date	
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
	
	)a

)
,PharmaReturnAmount as (
select a."Total" "PharmaReturnAmount" from(
select sum(coalesce(ar."OverallNetAmount",0)) "Total"
from "SaleReturnHeader" ar
left join "PharmacySaleHeader" srh on srh."PharmacySaleHeaderId" = ar."PharmacySaleHeaderId"
 where ar."ReturnDate" ::date >= f.weeks::text::date and ar."ReturnDate" ::date <= (f.weeks+ intervaldata)::text::date	
)a

)

,PharmaAmount as (
select 

	coalesce(a."PharmaSaleAmount",0) - coalesce(b. "PharmaReturnAmount",0) as  "PharmaAmount" 
from PharmaSaleAmount a ,PharmaReturnAmount b 
	

)
,finaldata as (select 
case when "Total" = 0 then 0 else round("AppointmentAmount"/"Total"*100,2) end "AppointmentAmount",
case when "Total" = 0 then 0 else round("AdmissionAmount"/"Total"*100,2) end "AdmissionAmount",
case when "Total" = 0 then 0 else round("LabAmount"/"Total"*100,2) end "LabAmount", 
case when "Total" = 0 then 0 else round("PharmacyAmount"/"Total"*100,2) end "PharmacyAmount",
"Total" 
from (
select distinct 
	ap."AppointmentAmount",
	ad."AdmissionAmount",
	lb."LabAmount",
sum(pa."PharmaAmount") over() "PharmacyAmount",	
coalesce(ap."AppointmentAmount",0)+coalesce(ad."AdmissionAmount",0)+coalesce(lb."LabAmount",0)
+coalesce(sum(pa."PharmaAmount") over(),0) "Total"

from  appointmentamount ap , admissionamount ad ,LabAmount lb ,PharmaAmount pa ) a)

select date_trunc('month', current_date)::date startdate ,f.weeks enddate,
       unnest(array['AppointmentAmount','AdmissionAmount','LabAmount', 'PharmacyAmount']) as "Name",
       unnest(array[ coalesce("AppointmentAmount",0),coalesce("AdmissionAmount",0),coalesce("LabAmount",0), coalesce("PharmacyAmount",0)]) as "Count" 
from finaldata;
end loop;
	RETURN QUERY
	with finalData as (select A.endDate,A.dname,sum(coalesce(A.countdata,0) )::numeric countdata from temp_table A group by A.endDate,A.dname)
	
	select A.startdate,B.dname,coalesce(B.countdata,0) from temp_date_table A
	left join finalData B on A.startdate=B.endDate;
	
	drop table temp_table;
	drop table temp_date_table;				
END;
$BODY$;


DROP FUNCTION IF EXISTS public."widget_Chart_OverAllRevenue1"(text, date, text, integer, integer);

CREATE OR REPLACE FUNCTION public."widget_Chart_OverAllRevenue1"(
	"chartType" text,
	"fromDate" date,
	"filterType" text,
	"displayCount" integer DEFAULT NULL::integer,
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Name" text, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
DECLARE
sql text := 'select "Date","Name", "Count"::numeric from ';
BEGIN
   IF "chartType"='Bar' THEN
      sql := sql || '"widget_BarChart_OverAllRevenue1"('''||"fromDate"||''','''||"filterType"||''', '''||"displayCount"||''','''||coalesce("locationId",0)||''')';
   
   ELSE 
     sql := sql || '"widget_PieChart_OverAllRevenue1"('''||"fromDate"||''','''||"filterType"||''','''||coalesce("locationId",0)||''')';
    
   END IF;
   raise notice 'query %', sql;
   RETURN QUERY EXECUTE sql
   ;
END
$BODY$;
----------------------------------------------------------------------Kalyan 07Sep2023----------------------------------------------------------------------
    alter table if exists "LabMainDetail"
    add column if not exists "TestPrecaution" character varying COLLATE pg_catalog."default";

----------------------------------------------------------------------------Radhika 07Sep2023-------------------------------------------------------------
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'DashboardWidget'
            )
        THEN
            UPDATE "DashboardWidget"
            SET "StoredProcedureName" = 'widget_Chart_Lab_Revenue1("chartType" text,"fromDate" date, "filterType" text, "displayCount" int4, "referenceId" int4, "locationId" int4)'
            where "DashboardWidgetId" = (select "DashboardWidgetId" from "DashboardWidget" where "StoredProcedureName" ilike '%widget_Chart_Lab_Revenue%');
        END IF ;
    END
   $$ ;


DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'DashboardWidget'
            )
        THEN
            UPDATE "DashboardWidget"
            SET "StoredProcedureName" = 'widget_Chart_OverAllRevenue1("chartType" text,"fromDate" date, "filterType" text, "displayCount" int4, "referenceId" int4, "locationId" int4)'
            where "DashboardWidgetId" = (select "DashboardWidgetId" from "DashboardWidget" where "StoredProcedureName" ilike '%widget_Chart_OverAllRevenue%');
        END IF ;
    END
   $$ ;
--------------------------------------------------------------------------------Mounika A 08Sep2023-------------------------------------------------------------------------

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 85,'EncounterTemplate',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'EncounterTemplate'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 86,'Practices',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'Practices'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 87,'PayType',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'PayType'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 88,'ReferralType',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'ReferralType'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 89,'ProviderMedication',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'ProviderMedication'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 90,'Relations',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'Relations'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 91,'OrderPrescription',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'OrderPrescription'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 92,'PayCategory',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'PayCategory'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 93,'PackageModule',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'PackageModule'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 94,'RoomCharge',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'RoomCharge'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 95,'ModuleCharge',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'ModuleCharge'
);

INSERT INTO public."LogType"("LogTypeId","LogTypeName", "Active")
SELECT 96,'DietConditions',true
WHERE
NOT EXISTS (
SELECT "LogTypeId" FROM public."LogType" WHERE  "LogTypeName" = 'DietConditions'
);

---------------------------------------------------------------------------
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'LogType'
            )
        THEN
            UPDATE "LogType"
            SET "LogTypeName" = 'Specializations'
            where "LogTypeId" = (select "LogTypeId" from "LogType" where "LogTypeName" = 'Specializations');
        END IF ;
    END
   $$ ;
----------------------------------manish 08Sep2023-----------------------------------------------------------------------
create table if not exists vendors."InventoryProductRequest"(
				"InventoryProductRequestId" serial primary key,
				"PharmacyProductId" int references "PharmacyProduct"("PharmacyProductId"),
				"RequestProductName" text,
				"ReasonForRequest" text,
				"RequestedQuantity" int,
				"RequestType" varchar(50),
				"CreatedBy" int references "Account"("AccountId"),
				"CreatedDate" timestamp without time zone,
				"PharmacyProductRequestId" bigint references vendors."PharmacyProductRequest"("PharmacyProductRequestId"),
				"RejectedBy" int references "Account"("AccountId"),
				"RejectedDate" timestamp without time zone,
				"RejectReason" text
);
alter table if exists vendors."InventoryProductRequest" 
add column if not exists "ModifiedBy" int references "Account"("AccountId"),
add column if not exists "ModifiedDate" timestamp without time zone,add column if not exists "DocumentUrl" text,
add column if not exists "LocationId" int references "Location"("LocationId");


alter table if exists vendors."PharmacyProductRequest" 
add column if not exists "RequestedQuantity" int default null;
------------------------------------------------------------Radhika 11Sep2023-------------------------------------------
DROP FUNCTION public."udf_fetch_LabOrderDetails"(integer, text, timestamp without time zone, timestamp without time zone, integer, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_fetch_LabOrderDetails"(
	"patientId" integer DEFAULT NULL::integer,
	"uMRNo" text DEFAULT NULL::text,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"doctorId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer,
	"labMainDetailId" integer DEFAULT NULL::integer)
    RETURNS TABLE("TotalItems" bigint, "newLabBookingHeaderId" integer, "createdDate" timestamp without time zone, "DoctorName" character varying, "PatientName" character varying, "UMRNo" character varying, "Status" text, "labBookingStatusId" integer, "LabMainDetailId" integer, "TestName" text, "StatusDate" timestamp without time zone, "ApprovedDate" timestamp without time zone) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
Declare 
BEGIN
return query

 with statusDate as (
                        select distinct "NewLabBookingHeaderId" as nl,"LabBookingStatusId" as lb,max("CreatedDate") as "StatusDate"
                        from "LabBookingTimeLine"	                       
	 where case when  "fromDate" is null then 1=1 else  "fromDate"::date <= "CreatedDate"::date and "CreatedDate"::date <= "toDate"::date end
	  group by  "NewLabBookingHeaderId","LabBookingStatusId"
                        )

SELECT count(nlbh.*) over () as "TotalItems",
                        nlbh."NewLabBookingHeaderId" as newLabBookingHeaderId, 
             nlbh."CreatedDate", prv."FullName"  as "DoctorName" ,
           nlbh."PatientName" , p."UMRNo",LS."Status", LS."LabBookingStatusId" as labBookingStatusId,
		   LN."LabMainDetailId",
		   LN."TestName",T."StatusDate",lrv."ApprovedDate"                                       
            							
                                    from "NewLabBookingHeader" nlbh
                                    join "NewLabBookingDetail" LBD on nlbh."NewLabBookingHeaderId"=LBD."NewLabBookingHeaderId"  
									--and nlbh."Active"<> false
                                    join "LabMainDetail" LN on LN."LabMainDetailId" = LBD."LabMainDetailId"
                                    join "LabDepartment" LD  on LD."LabDepartmentId"=LN."LabDepartmentId"
                                    join "LabBookingStatus" LS on LS."LabBookingStatusId" = LBD."LabBookingStatusId"
                                    join "Account" c on c."AccountId" = nlbh."CreatedBy" 
                                    join "Location" l ON l."LocationId" = nlbh."LocationId"
                                    left join "Patient" p ON p."PatientId" =nlbh."PatientId"
                                    left join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"
                                    left join "Department" PD on PD."DepartmentId"=prv."DepartmentId"
                                    left join statusDate T on T."nl"=nlbh."NewLabBookingHeaderId" and T."lb"=LBD."LabBookingStatusId"
                         			left join "LabReportVerification" lrv on lrv."NewLabBookingDetailId"=LBD."NewLabBookingDetailId"
where case when "uMRNo" ='' then 1=1   when "uMRNo" is null then 1=1  else p."UMRNo" ilike  '%'||"uMRNo"||'%' end and 
case when "doctorId" is null then 1=1 else nlbh."DoctorId"="doctorId" end and
	case when "labMainDetailId" is null then 1=1 else LBD."LabMainDetailId"="labMainDetailId" end and
	case when "patientId" is null then 1=1 else P."PatientId"="patientId" end and
 case when "fromDate" is null then 1=1 else  "fromDate"::date <= nlbh."CreatedDate"::date and nlbh."CreatedDate"::date <= "toDate"::date end
and case when "locationId" is null then 1=1 else nlbh."LocationId" = "locationId"::int end

;

END
$BODY$;

----------------------------------------------------------------------------Tej 13Sep2023--------------------------------------------
alter table if exists "Appointment" add column if not exists "SessionId" integer;

alter table if exists "Session" add column if not exists "SpecializationId" integer;

------------------------------------------------------------------Shiva 13Sep2023---------------------------------------------------------------------
 DROP FUNCTION IF EXISTS public.udf_lab_mothly_report(integer, timestamp without time zone, timestamp without time zone, integer);

CREATE OR REPLACE FUNCTION public.udf_lab_mothly_report(
	locationid integer DEFAULT NULL::integer,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	labmaindetailid integer DEFAULT NULL::integer)
    RETURNS TABLE("Order" integer, "TestName" text, "JAN" numeric, "FEB" numeric, "MAR" numeric, "APR" numeric, "MAY" numeric, "JUN" numeric, "JUL" numeric, "AUG" numeric, "SEP" numeric, "OCT" numeric, "NOV" numeric, "DEC" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
 
begin

return query

 with  "MonthReport" as(

Select T."TestName",count(T."TestName") AS "Count","MONTH", CASE WHEN "MONTH" = 1 THEN 'JAN' 
WHEN "MONTH" = 2 THEN 'FEB'
			WHEN "MONTH" = 3 THEN 'MAR'
			WHEN "MONTH" = 4 THEN 'APR'
			WHEN "MONTH" = 5 THEN 'MAY'
			WHEN "MONTH" = 6 THEN 'JUN'
			WHEN "MONTH" = 7 THEN 'JUL'
			WHEN "MONTH" = 8 THEN 'AUG'
			WHEN "MONTH" = 9 THEN 'SEP'
			WHEN "MONTH" = 10 THEN 'OCT'
			WHEN "MONTH" = 11 THEN 'NOV'
			WHEN "MONTH" = 12 THEN 'DEC'
	END AS "MonthName"   FROM 
(select lm."LabMainDetailId",ld."LabMainDetailId",lm."TestName",EXTRACT(MONTH FROM lt."CreatedDate") AS "MONTH"
from "NewLabBookingDetail" ld
join "LabMainDetail" lm on lm."LabMainDetailId"=ld."LabMainDetailId"
join "NewLabBookingHeader" lh on lh."NewLabBookingHeaderId"=ld."NewLabBookingHeaderId"
join "LabBookingTimeLine" lt on lt."NewLabBookingDetailId"=ld."NewLabBookingDetailId" 
and lh."NewLabBookingHeaderId"=lt."NewLabBookingHeaderId"and lt."LabBookingStatusId"=7  
 	where 1=1 and			 
	   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE lh."LocationId"=locationId END
	AND case when "fromDate" is null then 1=1 	else lt."CreatedDate" >= "fromDate" end 
	and case when "toDate" is null then 1=1 	else lt."CreatedDate" <= "toDate" end 
 and CASE WHEN (labMainDetailId IS NULL OR labMainDetailId=0) THEN 1=1 ELSE lm."LabMainDetailId"=labMainDetailId END
) T 
Group BY "MONTH",T."TestName" Order By "MONTH",T."TestName"
	 )
select 1 "Order",ts."TestName",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=1) "JAN",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=2) "FEB",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=3) "MAR",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=4) "APR",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=5) "MAY",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=6) "JUN",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=7) "JUL",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=8) "AUG",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=9) "SEP",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=10) "OCT",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=11) "NOV",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."TestName"=ts."TestName" and tsjan."MONTH"=12) "DEC"
from "MonthReport" ts
UNION
select DISTINCT 2 "Order",'TOTAL' "TestName",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."MONTH"=1) "JAN",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=2) "FEB",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."MONTH"=3) "MAR",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."MONTH"=4) "APR",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=5) "MAY",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=6) "JUN",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=7) "JUL",
(select sum("Count") from "MonthReport" tsJan WHERE tsjan."MONTH"=8) "AUG",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=9) "SEP",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=10) "OCT",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=11) "NOV",
(select sum("Count") from "MonthReport" tsJan WHERE  tsjan."MONTH"=12) "DEC"
from "MonthReport" ts
ORDER BY 1,2;
	end
$BODY$;

-----------------------------------------------------------------------------------
 DROP FUNCTION IF EXISTS public."udf_lab_TAT_Count_report"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_lab_TAT_Count_report"(
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	locationid integer DEFAULT NULL::integer,
	labmaindetailid integer DEFAULT NULL::integer)
    RETURNS TABLE("StartDate" text, "TestName" text, "DepartmentName" text, "LabCount" bigint, "AvgMinuts" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
 
begin

return query
                    Select   T."StartDate" , T."TestName" ,T."DepartmentName",Count(T."TestName") AS "LabCount",avg(T."Minuts") AS "AvgMinuts" FROM
                    (
                    select lmd."TestName",ld."DepartmentName",
                    (EXTRACT(YEAR FROM lbt."CreatedDate")::character varying ||'-'|| EXTRACT(MONTH FROM lbt."CreatedDate")::character varying ||'-'|| EXTRACT(day FROM lbt."CreatedDate")::character varying) AS "StartDate",
                    EXTRACT(EPOCH FROM (age(lbt."CreatedDate",lbtl."CreatedDate")))/60 "Minuts"
                    From "LabMainDetail" lmd
                    join "LabDepartment" ld on ld."LabDepartmentId"=lmd."LabDepartmentId"
                    join "NewLabBookingDetail" nlbd on nlbd."LabMainDetailId"=lmd."LabMainDetailId"
                    join "LabBookingTimeLine" lbtl on lbtl."NewLabBookingHeaderId"=nlbd."NewLabBookingHeaderId" 
                    and lbtl."LabBookingStatusId"=1
                    join "LabBookingTimeLine" lbt on lbt."NewLabBookingDetailId"=nlbd."NewLabBookingDetailId" 
                    and lbtl."NewLabBookingHeaderId"=lbt."NewLabBookingHeaderId"
                    and lbt."LabBookingStatusId"=7
	                	where 1=1 	--and  lbt."CreatedDate" >= '2023-09-01' and lbt."CreatedDate" <= '2023-09-12'
 	AND case when "fromDate" is null then 1=1 	else lbt."CreatedDate" >= "fromDate" end 
 	and case when "toDate" is null then 1=1 	else lbt."CreatedDate" <= "toDate" end
	and case when labMainDetailId is null then 1=1 	else lmd."LabMainDetailId" = labMainDetailId end
						
	                ) T	
	                Group By   T."StartDate" , T."TestName" ,T."DepartmentName"	
	                Order By   T."StartDate" , T."TestName" ,T."DepartmentName";
					
	end
$BODY$;

------------------------------------------------------------------------------------------------kalyan 13Sep2023--------------------------------------------------

INSERT INTO public."Lookup"("Name", "Description")
SELECT 'LabSampleUncollect','Reasons For Lab Sample Uncollect'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Lookup" WHERE "Name" = 'LabSampleUncollect'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'LabSampleUncollect'),'Wrong Selection',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'LabSampleUncollect') and "Name" = 'Wrong Selection'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'LabSampleUncollect'),'Vacutainer Broken',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'LabSampleUncollect') and "Name" = 'Vacutainer Broken'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'LabSampleUncollect'),'Something Went Wrong',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'LabSampleUncollect') and "Name" = 'Something Went Wrong'
);




INSERT INTO public."Lookup"("Name", "Description")
SELECT 'LabSampleReject','For Lab Sample Rejected Reasons'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Lookup" WHERE "Name" = 'LabSampleReject'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'LabSampleReject'),'Sample Broken',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'LabSampleReject') and "Name" = 'Sample Broken'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'LabSampleReject'),'Amount of Sample is not Enough',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'LabSampleReject') and "Name" = 'Amount of Sample is not Enough'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'LabSampleReject'),'Wrong Selection',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'LabSampleReject') and "Name" = 'Wrong Selection'
);

alter table if  exists "LabSampleCollectionDetail"
add column if not exists "UncollectComment" text COLLATE pg_catalog."default";


----------------------------------------------------------------------------RajaSekhar 13Sep2023---------------------------------------------------------
alter table if  exists "ObEncounter" 
add column if not exists "InductionForm" text;
----------------------------------------------------------------------------Manish 13Sep2023---------------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_FetchPatientsFilter_For_Appointment"(character varying, character varying, character varying, character varying);

CREATE OR REPLACE FUNCTION public."udf_FetchPatientsFilter_For_Appointment"(
	filter character varying DEFAULT NULL::text,
	"patientMobile" character varying DEFAULT NULL::text,
	"uMRNo" character varying DEFAULT NULL::text,
	"patientName" character varying DEFAULT NULL::text)
    RETURNS TABLE("PatientId" integer, "Salutation" character varying, "FirstName" text, "MiddleName" text, "LastName" text, "FullName" text, "DateOfBirth" date, "Age" smallint, "Gender" character, "UMRNo" character varying, "Email" character varying, "Mobile" character varying, "CountryId" integer, "ProfileImageUrl" text,"TempPatient" boolean, "HowDidYouKnowId" integer, "Active" boolean, "PaymentStatus" boolean, "ThumbnailUrl" text, "AppointmentDate" timestamp without time zone, "isActiveAppointmentExists" boolean, "isActiveAdmissionExists" boolean) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

with cts as (
select row_number() over(partition by a."PatientId" order by  a."AppointmentId" desc, a."AppointmentDate" desc )"Max" ,a."PatientId",a."AppointmentId" from "Appointment" a
join  "Patient" pat  on  a."PatientId"	=pat."PatientId"
where a."Active"=true 	 
	and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
	and	case when "uMRNo" is null then 1=1 else  pat."UMRNo"  ilike'%'|| "uMRNo"||'%' end
	and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
)
, maxapt as (
select a.* from "Appointment" a
join cts on a."AppointmentId"=cts."AppointmentId"
where "Max"=1)
,ctsadmission as (	
select distinct  max(a."AdmissionId") over(partition by a."PatientId"   )"MaxAdmissionId" ,a."PatientId",
	a."AppointmentId" from "Admission" a
join  "Patient" pat  on  a."PatientId"	=pat."PatientId"
where a."Active"=true 	 
	
	and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
	and	case when "uMRNo" is null then 1=1 else  pat."UMRNo"  ilike'%'|| "uMRNo"||'%' end
	and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
)

, maxadmision as (
	select a.* from "Admission" a
join ctsadmission cts on a."AdmissionId"=cts."MaxAdmissionId"
	)

SELECT DISTINCT pat."PatientId" ,
    pat."Salutation"  ,
    pat."FirstName"  ,
    pat."MiddleName"  ,
    pat."LastName"  ,
    pat."FullName"  ,
    pat."DateOfBirth" ,
    pat."Age"  ,
    pat."Gender"  ,
    pat."UMRNo"  ,
    pat."Email"  ,
    pat."Mobile" ,
    pat."CountryId"  ,
    pat."ProfileImageUrl"  ,
	pat."TempPatient",
	pat."HowDidYouKnowId",
   -- pat."ThumbnailUrl"  ,
    pat."Active"  ,
	pat."PaymentStatus",
(CASE WHEN pat."ThumbnailUrl" IS NOT NULL THEN CONCAT('https://hims-qa.s3.amazonaws.com/', pat."Guid", '/', pat."ThumbnailUrl") ELSE NULL END) AS "ThumbnailUrl"
,(max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId",apt."AppointmentDate")::text)::timestamp as "AppointmentDate",
(case when (max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId")::text)::timestamp > now() at time zone 'UTC-5:30' then true else false end)"isActiveAppointmentExists"
,(case when max(adm."AdmissionId")over(partition by adm."PatientId") is  null  then false 
	   when max(adm."AdmissionId")over(partition by adm."PatientId") is not null and max(dc."DischargeId")over(partition by pat."PatientId") is  null  then true 
	   when max(adm."AdmissionId")over(partition by adm."PatientId") is not null and max(dc."DischargeId")over(partition by pat."PatientId") is not null  then false end
	  )"isActiveAdmissionExists"
FROM "Patient" pat  
left join maxapt apt on apt."PatientId" = pat."PatientId" and apt."Status" <> 'C' and apt."Active"=true
left join maxadmision adm on adm."PatientId" = pat."PatientId" and adm."Active"=true
left join "Discharge" dc on dc."AdmissionId" = adm."AdmissionId"
 WHERE  pat."Active" IS TRUE 
 
and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
and	case when "uMRNo" is null then 1=1 else  pat."UMRNo"  ilike'%'|| "uMRNo"||'%' end
and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
;

END
$BODY$;

create table if not exists "CallHistory" (
	"Id" SERIAL PRIMARY KEY,	
	"MobileNumber" VARCHAR,
	"FirstName" VARCHAR,
	"LastName" VARCHAR,
	"Comments" VARCHAR,
	"CallStart" text,
	"CallEnd" text,
	"CallDuration" text,
	"Type" integer,
	"CreatedDate" timestamp without time zone,
	"CreatedBy" integer,
	"ModifiedBy" integer,
	"ModifiedDate" timestamp without time zone,
	"IsActive" boolean NOT NULL
	);

create table if not exists "ContactDetails" (
	"Id" SERIAL PRIMARY KEY,	
	"Details" text,
	"PatientId" integer,
	"Type" integer,
	"CreatedDate" timestamp without time zone,
	"CreatedBy" integer,
	"ModifiedBy" integer,
	"ModifiedDate" timestamp without time zone,
	"IsActive" boolean NOT NULL
	);

create table if not exists "FeedbackDetails" (
	"Id" SERIAL PRIMARY KEY,	
	"MobileNumber" VARCHAR,
	"PatientName" VARCHAR,
	"Rating" integer,
	"Comments" VARCHAR,
	"Type" integer,
	"CreatedDate" timestamp without time zone,
	"CreatedBy" integer,
	"ModifiedBy" integer,
	"ModifiedDate" timestamp without time zone,
	"IsActive" boolean NOT NULL
	);

DROP FUNCTION IF EXISTS public."udf_FetchPatients_For_QuickScheduleFollowUp"(character varying, character varying, character varying, character varying);

CREATE OR REPLACE FUNCTION public."udf_FetchPatients_For_QuickScheduleFollowUp"(
	filter character varying DEFAULT NULL::text,
	"patientMobile" character varying DEFAULT NULL::text,
	"patientName" character varying DEFAULT NULL::text,
	"urlLink" character varying DEFAULT NULL::text)
    RETURNS TABLE("PatientId" integer, "Salutation" character varying, "FirstName" text, "MiddleName" text, "LastName" text, "FullName" text, "DateOfBirth" date, "Age" smallint, "Gender" character, "UMRNo" character varying, "Email" character varying, "Mobile" character varying, "CountryId" integer, "ProfileImageUrl" text, "Active" boolean, "PaymentStatus" boolean, "HowDidYouKnowId" integer, "EducationId" integer, "OccupationId" integer, "ProviderId" integer, "ProviderName" character varying, "ThumbnailUrl" text, "AppointmentDate" timestamp without time zone, "isActiveAppointmentExists" boolean, "isActiveAdmissionExists" boolean, "HWCName" character varying, "HWCPatientId" integer, "Description" text, "RowColor" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

with cts as (
select row_number() over(partition by a."PatientId" order by  a."AppointmentId" desc,
						 a."AppointmentDate" desc )"Max" ,a."PatientId",a."AppointmentId" 
	from "Appointment" a
join  "Patient" pat  on  a."PatientId"	=pat."PatientId"
	join "Provider" pr on a."ProviderId" = pr."ProviderId"
where a."Active"=true 	 
	--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
	and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
	and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
)
, maxapt as (
select a.* from "Appointment" a
join cts on a."AppointmentId"=cts."AppointmentId"
where "Max"=1)
,ctsadmission as (	
select distinct  max(a."AdmissionId") over(partition by a."PatientId"   )"MaxAdmissionId" ,a."PatientId",
	a."AppointmentId" from "Admission" a
join  "Patient" pat  on  a."PatientId"	=pat."PatientId"
where a."Active"=true 	 
	--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%') || "filter"||'%' end
	and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
	and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
)

, maxadmision as (
	select a.* from "Admission" a
join ctsadmission cts on a."AdmissionId"=cts."MaxAdmissionId"
	)

SELECT DISTINCT pat."PatientId" ,
    pat."Salutation"  ,
    pat."FirstName"  ,
    pat."MiddleName"  ,
    pat."LastName"  ,
    pat."FullName"  ,
    pat."DateOfBirth" ,
    pat."Age"  ,
    pat."Gender"  ,
    pat."UMRNo"  ,
    pat."Email"  ,
    pat."Mobile" ,
    pat."CountryId"  ,
    pat."ProfileImageUrl"  ,
   -- pat."ThumbnailUrl"  ,
    pat."Active"  ,
	pat."PaymentStatus",
	pat."HowDidYouKnowId",
	pat."EducationId",
	pat."OccupationId",
	apt."ProviderId",
	pr."FullName" as "ProviderName",
(CASE WHEN pat."ThumbnailUrl" IS NOT NULL THEN CONCAT("urlLink", pat."Guid", '/', pat."ThumbnailUrl") ELSE NULL END) AS "ThumbnailUrl"
,(max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId",apt."AppointmentDate")::text)::timestamp as "AppointmentDate",
(case when (max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId")::text)::timestamp > now() at time zone 'UTC-5:30' then true else false end)"isActiveAppointmentExists"
,(case when max(adm."AdmissionId")over(partition by adm."PatientId") is  null  then false 
	   when max(adm."AdmissionId")over(partition by adm."PatientId") is not null and max(dc."DischargeId")over(partition by pat."PatientId") is  null  then true 
	   when max(adm."AdmissionId")over(partition by adm."PatientId") is not null and max(dc."DischargeId")over(partition by pat."PatientId") is not null  then false end
	  )"isActiveAdmissionExists", HWC."HWCName",HWC."HWCPatientId", HWC."Description", HWC."RowColor"
FROM "Patient" pat  
left join maxapt apt on apt."PatientId" = pat."PatientId" and apt."Status" <> 'C' and apt."Active"=true
left join "Provider" pr on pr."ProviderId" = apt."ProviderId"
left join maxadmision adm on adm."PatientId" = pat."PatientId" and adm."Active"=true
left join "Discharge" dc on dc."AdmissionId" = adm."AdmissionId"
left join "HWCPatient"  HWC on HWC."HWCPatientId" = pat."HWCPatientId"
 WHERE  pat."Active" IS TRUE 
--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
;

END
$BODY$;


INSERT INTO public."HowDidYouKnow"("Name", "Active", "CreatedBy","CreatedDate")
SELECT 'CALL CENTER', 'true', '6776', '2022-11-28 00:00:00'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."HowDidYouKnow" WHERE "Name" = 'CALL CENTER'
);

-------------------------------------------------------------------Mounika A 13Sep2023--------------------------------------------------------------------------------
drop  FUNCTION if exists "UDF_Expiry"( int,int,int,date,date);

create OR REPLACE FUNCTION "UDF_Expiry"(locationId int,pharmacyWareHouseId int,retailPharmacyId int,fromDate date,toDate date)
    RETURNS TABLE("BatchNumber" character varying, "ExpiryDate" date, "QuantityIn" integer, "PurchaseRate" numeric,"Mrp" numeric,"ProductName"  character varying,"LossAmount" numeric)
	LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin

 if retailPharmacyId is null then
	 
	return query   select RS."BatchNumber",RS."ExpiryDate"::date,RS."QuantityIn",RS."PurchaseRate",RS."Mrp"
	,PP."ProductName",(RS."PurchaseRate"*RS."QuantityIn") as "LossAmount"
 from "PharmacyStock" RS
left join "PharmacyProduct" PP on PP."PharmacyProductId"=RS."PharmacyProductId"
left join "PharmacyWareHouse" PW on PW."PharmacyWareHouseId"=RS."PharmacyWareHouseId"
where   PW."LocationId" = locationId 
and PW."PharmacyWareHouseId"=pharmacyWareHouseId 
and  RS."ExpiryDate"::DATE >= fromDate::DATE 
and  RS."ExpiryDate"::date  <= toDate::DATE ;
         
else		  
  return query  select  RS."BatchNumber",RS."ExpiryDate"::date,RS."QuantityIn",RS."PurchaseRate",RS."Mrp",PP."ProductName",(RS."PurchaseRate"*RS."QuantityIn") as "LossAmount"
               		from "PharmacyRetailStock" RS
                    left join "PharmacyProduct" PP on PP."PharmacyProductId" = RS."PharmacyProductId"
                    left join "RetailWareHouseLink" PS on PS."RetailWareHouseLinkId" = RS."RetailWareHouseLinkId"
                    where  PS."RetailPharmacyId" =retailPharmacyId 
					and  PS."PharmacyWareHouseId"= pharmacyWareHouseId 
					and RS."ExpiryDate"::DATE >= fromDate::DATE 
					and  RS."ExpiryDate"::date  <= toDate::DATE;
					   end if;
end;
$BODY$;

------------------------------------------------------------------Shivani 13Sep2023--------------------------------------------------------------------------------


create sequence IF NOT EXISTS "PackageDocument_PackageDocumentId_seq";


CREATE TABLE IF NOT EXISTS public."PackageDocument"
(
    "PackageDocumentId" integer NOT NULL DEFAULT nextval('"PackageDocument_PackageDocumentId_seq"'::regclass),
    "PackageModuleId" integer NOT NULL,
    "DocumentName" character varying(100)  NOT NULL,
    "ContentType" character varying(50)  NOT NULL,
    "Size" double precision NOT NULL,
    "DocumentUrl" text NOT NULL,
    "ThumbnailUrl" text  NOT NULL,
    "UploadedDate" timestamp(6) without time zone NOT NULL,
    "UploadedBy" integer NOT NULL,
    CONSTRAINT "PackageDocumentId_pkey" PRIMARY KEY ("PackageDocumentId"),
    CONSTRAINT "FK_PackageDocument_PackageModuleId" FOREIGN KEY ("PackageModuleId")
        REFERENCES public."PackageModule" ("PackageModuleId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
	CONSTRAINT "FK_PackageDocument_UploadedBy" FOREIGN KEY ("UploadedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
);

create sequence IF NOT EXISTS "AdmissionChangeRequestType_AdmissionChangeRequestType_Id_seq";


CREATE TABLE IF NOT EXISTS public."AdmissionChangeRequestType"
(
    "AdmissionChangeRequestTypeId" integer NOT NULL DEFAULT nextval('"AdmissionChangeRequestType_AdmissionChangeRequestType_Id_seq"'::regclass),
    "ChangeRequestType" character varying(100),
    "Active" boolean DEFAULT false,
    "CreatedBy" bigint NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    CONSTRAINT "AdmissionChangeRequestType_pkey" PRIMARY KEY ("AdmissionChangeRequestTypeId"),
    CONSTRAINT "FK_AdmissionChangeRequestType_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);


create sequence IF NOT EXISTS "AdmissionTransferRequest_AdmissionTransferRequest_Id_seq";

CREATE TABLE IF NOT EXISTS public."AdmissionTransferRequest"
(
    "AdmissionTransferRequestId" integer NOT NULL DEFAULT nextval('"AdmissionTransferRequest_AdmissionTransferRequest_Id_seq"'::regclass),
    "AdmissionId" bigint NOT NULL,
    "DoctorUnitMasterId" bigint,
    "ChargeCategories" integer[],
    "Active" boolean DEFAULT false,
    "CreatedBy" bigint NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ApprovedBy" bigint,
    "ApprovedDate" timestamp without time zone,
    "LocationId" integer NOT NULL,
    "AdmissionChangeRequestTypeId" integer NOT NULL,
    "RequestComments" text COLLATE pg_catalog."default",
    CONSTRAINT "AdmissionTransferRequest_pkey" PRIMARY KEY ("AdmissionTransferRequestId"),
    CONSTRAINT "FK_AdmissionTransferRequest_AdmissionChangeRequestTypeId" FOREIGN KEY ("AdmissionChangeRequestTypeId")
        REFERENCES public."AdmissionChangeRequestType" ("AdmissionChangeRequestTypeId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_AdmissionTransferRequest_AdmissionId" FOREIGN KEY ("AdmissionId")
        REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_AdmissionTransferRequest_ApprovedBy" FOREIGN KEY ("ApprovedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_AdmissionTransferRequest_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_AdmissionTransferRequest_DoctorUnitMasterId" FOREIGN KEY ("DoctorUnitMasterId")
        REFERENCES public."DoctorUnitMaster" ("DoctorUnitMasterId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_AdmissionTransferRequest_LocationId" FOREIGN KEY ("LocationId")
        REFERENCES public."Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);






INSERT INTO public."AdmissionChangeRequestType"("ChangeRequestType", "Active", "CreatedBy", "CreatedDate")
SELECT 'Bed', true, 6776, now()
WHERE
NOT EXISTS (
SELECT "ChangeRequestType" FROM public."AdmissionChangeRequestType" WHERE "ChangeRequestType" = 'Bed'
);

INSERT INTO public."AdmissionChangeRequestType"("ChangeRequestType", "Active", "CreatedBy", "CreatedDate")
SELECT 'DoctorUnit', true, 6776, now()
WHERE
NOT EXISTS (
SELECT "ChangeRequestType" FROM public."AdmissionChangeRequestType" WHERE "ChangeRequestType" = 'Bed'
);


-----------------------------------------------------------------Sandeeep 13Sep2023----------------------------------------------------------------------------------
ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "DiscountType" character varying(1) COLLATE pg_catalog."default";

ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "DiscountPercentage" numeric(8,2);

ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "DiscountAmount" numeric(8,2);

ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "Discount" numeric(8,2) NOT NULL DEFAULT 0;

ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "DiscountType" character varying(1) COLLATE pg_catalog."default";

ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "DiscountPercentage" numeric(8,2);

ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "DiscountAmount" numeric(8,2);

ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "Discount" numeric(8,2) NOT NULL DEFAULT 0;
-------------------------------------------------------------Sai Pavan 14Sep2023-------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public."WhatsAppTickets"
(
    "TicketId" integer NOT NULL DEFAULT nextval('"WhatsAppTickets_TicketId_seq"'::regclass),
    "TicketNo" text COLLATE pg_catalog."default",
    "Mobile" text COLLATE pg_catalog."default",
    "Name" text COLLATE pg_catalog."default",
    "Regarding" text COLLATE pg_catalog."default",
    "Solved" boolean,
    "CreatedDate" timestamp with time zone DEFAULT now(),
    "ModifiedBy" integer,
    "ModifiedDate" timestamp(6) without time zone,
    CONSTRAINT "WhatsAppTickets_pkey" PRIMARY KEY ("TicketId")
);

-------------------------------------------------------------------------------Manish 14Sep2023---------------------------------------------------------------------
INSERT INTO vendors."TendorStatus" ("Status")
SELECT 'Quotation Selected' as "Status"
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE "Status" = 'Quotation Selected'
);

-------------------------------------------------------------------------------Sravani 14Sep2023---------------------------------------------------------------------
INSERT INTO "ScanLogType"("LogTypeName","Active")
SELECT 'ScanScroll',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM "ScanLogType" WHERE "LogTypeName" = 'ScanScroll'
);
-------------------------------------------------------------------------------Mahesh 14Sep2023---------------------------------------------------------------------
INSERT INTO "LogType"("LogTypeId","LogTypeName","Active")
SELECT 98,'WhatsAppTickets',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM "LogType" WHERE "LogTypeName" = 'WhatsAppTickets'
);

-------------------------------------------------------------------------------Manish 14Sep2023---------------------------------------------------------------------
alter table if exists vendors."PharmacyProductApproval" 
add column if not exists "ProductForQuotationHeaderId" bigint references vendors."ProductForQuotationHeader"("ProductForQuotationHeaderId"); 
-------------------------------------------------------------------------------Subramanyam 14Sep2023---------------------------------------------------------------------
INSERT INTO "PharmacyLogType"("PharmacyLogTypeId","LogTypeName","Active")
SELECT 23,'Product_Type',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM "PharmacyLogType" WHERE "LogTypeName" = 'Product_Type'
);
INSERT INTO "PharmacyLogType"("PharmacyLogTypeId","LogTypeName","Active")
SELECT 24,'Product_Sub_Type',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM "PharmacyLogType" WHERE "LogTypeName" = 'Product_Sub_Type'
);
INSERT INTO "PharmacyLogType"("PharmacyLogTypeId","LogTypeName","Active")
SELECT 25,'Central_Store_Stock',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM "PharmacyLogType" WHERE "LogTypeName" = 'Central_Store_Stock'
);
INSERT INTO "PharmacyLogType"("PharmacyLogTypeId","LogTypeName","Active")
SELECT 26,'Retail_Store_Stock',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM "PharmacyLogType" WHERE "LogTypeName" = 'Retail_Store_Stock'
);

   DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'PharmacyLogType'
            )
        THEN
            UPDATE "PharmacyLogType"
            SET "LogTypeName" = 'Product'
            where "PharmacyLogTypeId"=7;
        END IF ;
    END
   $$ ;
-------------------------------------------------------------------------------Shivani 14Sep2023-------------------------------------------------------------
alter table if exists "PatientMedicationDetail" 
add column  if not exists "Remark" text;
-------------------------------------------------------------------------------Shiva 14Sep2023-------------------------------------------------------------
DROP FUNCTION IF EXISTS public.udf_doctor_new_revenue(integer, integer, date, date);

CREATE OR REPLACE FUNCTION public.udf_doctor_new_revenue(
	providerid integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date)
    RETURNS TABLE("AccountId" integer, "DoctorName" text, "AppointmentCashTotal" numeric, "AppointmentCardTotal" numeric, "AppointmentUPITotal" numeric, "AppointmentOnlineTotal" numeric, "AppointmentChequeTotal" numeric, "AppointmentPaytmTotal" numeric, "AppointmentOtherTotal" numeric, "AppointmentCardsSwipeTotal" numeric, "AppointmentCardStandAloneTotal" numeric, "AppointmentCardUPITotal" numeric, "AppointmentCardsGPayTotal" numeric, "AppointmentCashDrawerTotal" numeric, "AppointmentCashChequeTotal" numeric, "AppointmentCashDDTotal" numeric, "AppointmentWalletPaytmOfflineTotal" numeric, "AppointmentWalletPhonePeOfflineTotal" numeric, "AppointmentCashRemoteDepositTotal" numeric, "AppointmentWalletPaytmDQRTotal" numeric, "AppointmentAmount" numeric, "AdmissionCashTotal" numeric, "AdmissionCardTotal" numeric, "AdmissionUPITotal" numeric, "AdmissionOnlineTotal" numeric, "AdmissionChequeTotal" numeric, "AdmissionPaytmTotal" numeric, "AdmissionOtherTotal" numeric, "AdmissionCardsSwipeTotal" numeric, "AdmissionCardStandAloneTotal" numeric, "AdmissionCardUPITotal" numeric, "AdmissionCardsGPayTotal" numeric, "AdmissionCashDrawer" numeric, "AdmissionCashChequeTotal" numeric, "AdmissionCashDDTotal" numeric, "AdmissionWalletPaytmOfflineTotal" numeric, "AdmissionWalletPhonePeOfflineTotal" numeric, "AdmissionCashRemoteDepositTotal" numeric, "AdmissionWalletPaytmDQRTotal" numeric, "AdmissionAmount" numeric, "LabCash" numeric, "LabCard" numeric, "LabUPI" numeric, "LabOnline" numeric, "LabCheque" numeric, "LabPaytm" numeric, "Other" numeric, "CardsSwipe" numeric, "CardStandAlone" numeric, "CardUPI" numeric, "CardsGPay" numeric, "CashCashDrawer" numeric, "CashCheque" numeric, "CashDD" numeric, "WalletPaytmOffline" numeric, "WalletPhonePeOffline" numeric, "CashRemoteDeposit" numeric, "WalletPaytmDQR" numeric, "LabAmount" numeric, "PharmacySaleCash" numeric, "PharmacySaleCard" numeric, "PharmacySaleUPI" numeric, "PharmacySaleOnline" numeric, "PharmacySaleCheque" numeric, "PharmacySalePaytm" numeric, "PharmacySaleOther" numeric, "PharmacySaleCardsSwipe" numeric, "PharmacySaleCardStandAlone" numeric, "PharmacySaleCardUPI" numeric, "PharmacySaleCardsGPay" numeric, "PharmacySaleCashCashDrawer" numeric, "PharmacySaleCashCheque" numeric, "PharmacySaleCashDD" numeric, "PharmacySaleWalletPaytmOffline" numeric, "PharmacySaleWalletPhonePeOffline" numeric, "PharmacySaleCashRemoteDeposit" numeric, "PharmacySaleWalletPaytmDQR" numeric, "PharmacyAmount" numeric, "TotalCash" numeric, "TotalCard" numeric, "TotalUPI" numeric, "TotalOnline" numeric, "TotalCheque" numeric, "TotalPaytm" numeric, "OtherTotal" numeric, "CardsSwipeTotal" numeric, "CardStandAloneTotal" numeric, "CardUPITotal" numeric, "CardsGPayTotal" numeric, "CashDrawer" numeric, "CashChequeTotal" numeric, "CashDDTotal" numeric, "WalletPaytmOfflineTotal" numeric, "WalletPhonePeOfflineTotal" numeric, "CashRemoteDepositTotal" numeric, "WalletPaytmDQRTotal" numeric, "Total" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
  return query 

with accountdata as (
select distinct P."ProviderId",P."FullName" "DoctorName"
from "Provider" P
	join "ProviderAvailability" PL on PL."ProviderId"=P."ProviderId"    
   --  where P."ProviderId"=353    and PL."LocationId"=2
where case when providerId is null then 1=1 else P."ProviderId"=providerId end 
	and case when "locationId" is null then 1=1 else PL."LocationId"= "locationId" end   
)
-- select * from "Provider"=288
-- select * from "ProviderAvailability"
,actappointmentamount as (
	
	select a."ProviderId",sum(A."CashTotal") "AppointmentCashTotal",sum(A."CardTotal") "AppointmentCardTotal",
	sum(A."UPITotal") "AppointmentUPITotal",sum(A."OnlineTotal") "AppointmentOnlineTotal",
	sum(A."ChequeTotal") "AppointmentChequeTotal",sum(A."PaytmTotal") "AppointmentPaytmTotal",

   sum(A."OtherTotal") "AppointmentOtherTotal",    
    sum(A."CardsSwipeTotal") "AppointmentCardsSwipeTotal",
    sum(A."CardStandAloneTotal") "AppointmentCardStandAloneTotal",
    sum(A."CardUPITotal") "AppointmentCardUPITotal",
    sum(A."CardsGPayTotal") "AppointmentCardsGPayTotal",
    sum(A."CashCashDrawerTotal") "AppointmentCashDrawer",
    sum(A."CashChequeTotal") "AppointmentCashChequeTotal",
    sum(A."CashDDTotal") "AppointmentCashDDTotal",
    sum(A."WalletPaytmOfflineTotal") "AppointmentWalletPaytmOfflineTotal",
    sum(A."WalletPhonePeOfflineTotal") "AppointmentWalletPhonePeOfflineTotal",
    sum(A."CashRemoteDepositTotal") "AppointmentCashRemoteDepositTotal",
    sum(A."WalletPaytmDQRTotal") "AppointmentWalletPaytmDQRTotal",
    
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+sum(A."PaytmTotal")+
    
    sum(A."OtherTotal")+sum(A."CardsSwipeTotal") +sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardsGPayTotal") +
    sum(A."CashCashDrawerTotal") +sum(A."CashChequeTotal") +sum(A."CashDDTotal") +sum(A."WalletPaytmOfflineTotal") +
    sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal") appointmentamount
    
	from (
   select  ap."ProviderId"  "ProviderId",   
   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
   case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal" ,
	case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
   case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
   case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
   case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",	

   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardsSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end "CardStandAloneTotal" ,
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal" ,
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end "CardsGPayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end "CashCashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end "WalletPhonePeOfflineTotal" ,
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end "WalletPaytmDQRTotal"
        
		from "Receipt" A
    join "Appointment" ap on  ap."AppointmentId" =A."RespectiveId"  and A."ReceiptAreaTypeId"=4
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
    and ap."Active" =true	
   where 
	case when providerId is null then 1=1 else ap."ProviderId"=providerId end   and 
											A."ReceiptTypeId"=1 	
	and A."Active"<>false and A."RespectiveId" is not null  
AND CASE WHEN ("locationId" IS NULL OR "locationId"=0) THEN 1=1 ELSE ap."LocationId"="locationId" END 
	and coalesce(A."IsRefunded",false) <>true and ap."Status" <> 'C' 
	and	case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end	
	)a		
	group by  a."ProviderId"		
)
,refundappointmentamount as (
	
	select a."ProviderId" ,
	sum(A."CashTotal") "AppointmentRefCashTotal",sum(A."CardTotal") "AppointmentRefCardTotal",
	sum(A."UPITotal") "AppointmentRefUPITotal",sum(A."OnlineTotal") "AppointmentRefOnlineTotal",
	sum(A."ChequeTotal") "AppointmentRefChequeTotal",sum(A."PaytmTotal") "AppointmentRefPaytmTotal",
    
     sum(A."OtherTotal") "AppointmentRefOtherTotal",    
    sum(A."CardsSwipeTotal") "AppointmentRefCardsSwipeTotal",
    sum(A."CardStandAloneTotal") "AppointmentRefCardStandAloneTotal",
    sum(A."CardUPITotal") "AppointmentRefCardUPITotal",
    sum(A."CardsGPayTotal") "AppointmentRefCardsGPayTotal",
    sum(A."CashCashDrawerTotal") "AppointmentRefCashDrawer",
    sum(A."CashChequeTotal") "AppointmentRefCashChequeTotal",
    sum(A."CashDDTotal") "AppointmentRefCashDDTotal",
    sum(A."WalletPaytmOfflineTotal") "AppointmentRefWalletPaytmOfflineTotal",
    sum(A."WalletPhonePeOfflineTotal") "AppointmentRefWalletPhonePeOfflineTotal",
    sum(A."CashRemoteDepositTotal") "AppointmentRefCashRemoteDepositTotal",
    sum(A."WalletPaytmDQRTotal") "AppointmentRefWalletPaytmDQRTotal",
    
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")+
    
    sum(A."OtherTotal")+sum(A."CardsSwipeTotal") +sum(A."CardStandAloneTotal")+sum(A."CardUPITotal") +sum(A."CardsGPayTotal") +
    sum(A."CashCashDrawerTotal") +sum(A."CashChequeTotal") +sum(A."CashDDTotal") +sum(A."WalletPaytmOfflineTotal") +
    sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")  refappointmentamount
	from (
    select  ap."ProviderId"  "ProviderId",
		   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
          case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal",
			case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
          case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",								
		case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
          case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",

   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardsSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end "CardStandAloneTotal" ,
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal" ,
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end "CardsGPayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end "CashCashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end "WalletPhonePeOfflineTotal" ,
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end "WalletPaytmDQRTotal" 
        
		 from "Receipt" A
    join "Appointment" ap on ap."AppointmentId" =A."RespectiveId" and A."ReceiptAreaTypeId"=5
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
   and ap."Status" <> 'C'   and ap."Active" =true
	
   where case when providerId is null then 1=1 else ap."ProviderId"=providerId end    
	
	and A."Active"<>false and A."RespectiveId" is not null 
AND CASE WHEN ("locationId" IS NULL OR "locationId"=0) THEN 1=1 ELSE ap."LocationId"="locationId" END  
	and coalesce(A."IsRefunded",false) = true 
	and case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end	
	) a
	group by  a."ProviderId"	
	
)

,appointmentamount as (
select  A."ProviderId",
	coalesce(A."AppointmentCashTotal",0) - coalesce(B."AppointmentRefCashTotal",0) as "AppointmentCashTotal" ,
	coalesce(A."AppointmentCardTotal",0) - coalesce(B."AppointmentRefCardTotal",0) as "AppointmentCardTotal" ,	
	coalesce(A."AppointmentUPITotal",0) - coalesce(B."AppointmentRefUPITotal",0) as "AppointmentUPITotal" ,
	coalesce(A."AppointmentOnlineTotal",0) - coalesce(B."AppointmentRefOnlineTotal",0) as "AppointmentOnlineTotal" ,
	coalesce(A."AppointmentChequeTotal",0) - coalesce(B."AppointmentRefChequeTotal",0) as "AppointmentChequeTotal" ,
	coalesce(A."AppointmentPaytmTotal",0) - coalesce(B."AppointmentRefPaytmTotal",0) as "AppointmentPaytmTotal" ,
    
     coalesce(A."AppointmentOtherTotal",0) - coalesce(B."AppointmentRefOtherTotal",0) as "AppointmentOtherTotal",
    coalesce(A."AppointmentCardsSwipeTotal",0)- coalesce(B."AppointmentRefCardsSwipeTotal",0) as "AppointmentCardsSwipeTotal",
    coalesce(A."AppointmentCardStandAloneTotal",0)-coalesce(B."AppointmentRefCardStandAloneTotal",0) as "AppointmentCardStandAloneTotal",
    coalesce(A."AppointmentCardUPITotal",0)-coalesce(B."AppointmentRefCardUPITotal",0) as "AppointmentCardUPITotal",
    coalesce(A."AppointmentCardsGPayTotal",0)-coalesce(B."AppointmentRefCardsGPayTotal",0) as "AppointmentCardsGPayTotal",
    coalesce(A."AppointmentCashDrawer",0)-coalesce(B."AppointmentRefCashDrawer",0) as "AppointmentCashDrawerTotal",
    coalesce(A."AppointmentCashChequeTotal",0)-coalesce(B."AppointmentRefCashChequeTotal",0) as "AppointmentCashChequeTotal",
    coalesce(A."AppointmentCashDDTotal",0)-coalesce(B."AppointmentRefCashDDTotal",0) as "AppointmentCashDDTotal",
    coalesce(A."AppointmentWalletPaytmOfflineTotal",0)-coalesce(B."AppointmentRefWalletPaytmOfflineTotal",0) as "AppointmentWalletPaytmOfflineTotal",
    coalesce(A."AppointmentWalletPhonePeOfflineTotal",0)-coalesce(B."AppointmentRefCardsSwipeTotal",0) as "AppointmentWalletPhonePeOfflineTotal",
    coalesce(A."AppointmentCashRemoteDepositTotal",0)-coalesce(B."AppointmentRefCashRemoteDepositTotal",0) as "AppointmentCashRemoteDepositTotal",
    coalesce(A."AppointmentWalletPaytmDQRTotal",0)-coalesce(B."AppointmentRefCardsSwipeTotal",0) as "AppointmentWalletPaytmDQRTotal",
    
    	
	coalesce(A.appointmentamount,0) - coalesce(B.refappointmentamount,0) as "AppointmentAmount" 
	from actappointmentamount A
	left join refundappointmentamount B on A."ProviderId"=B."ProviderId"		
)

,
actadmissionamount as (
	
	select a."ProviderId" , sum(A."CashTotal") "AdmissionCashTotal",sum(A."CardTotal") "AdmissionCardTotal",
	sum(A."UPITotal") "AdmissionUPITotal",sum(A."OnlineTotal") "AdmissionOnlineTotal",
	sum(A."ChequeTotal") "AdmissionChequeTotal",sum(A."PaytmTotal") "AdmissionPaytmTotal",
    
    sum(A."OtherTotal") "AdmissionOtherTotal",    
    sum(A."CardsSwipeTotal") "AdmissionCardsSwipeTotal",
    sum(A."CardStandAloneTotal") "AdmissionCardStandAloneTotal",
    sum(A."CardUPITotal") "AdmissionCardUPITotal",
    sum(A."CardsGPayTotal") "AdmissionCardsGPayTotal",
    sum(A."CashCashDrawerTotal") "AdmissionCashDrawer",
    sum(A."CashChequeTotal") "AdmissionCashChequeTotal",
    sum(A."CashDDTotal") "AdmissionCashDDTotal",
    sum(A."WalletPaytmOfflineTotal") "AdmissionWalletPaytmOfflineTotal",
    sum(A."WalletPhonePeOfflineTotal") "AdmissionWalletPhonePeOfflineTotal",
    sum(A."CashRemoteDepositTotal") "AdmissionCashRemoteDepositTotal",
    sum(A."WalletPaytmDQRTotal") "AdmissionWalletPaytmDQRTotal",
    
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")+
    
    sum(A."OtherTotal")+sum(A."CardsSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardsGPayTotal")+ 
    sum(A."CashCashDrawerTotal")+sum(A."CashChequeTotal") +sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+ 
    sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal") "AdmissionAmount" 
	from (
select ad."ProviderId" "ProviderId" ,
   case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
   case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal",									  
	case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
   case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal",		
case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
   case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal",
        
        case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end "OtherTotal",
   case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardsSwipeTotal",
   case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end "CardStandAloneTotal" ,
   case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal" ,
   case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end "CardsGPayTotal",
   case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end "CashCashDrawerTotal",
   case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
   case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
   case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end "WalletPaytmOfflineTotal",
   case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end "WalletPhonePeOfflineTotal" ,
   case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end "CashRemoteDepositTotal",
   case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end "WalletPaytmDQRTotal" 
        
        
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false and adr."ReceiptAreaTypeId"=12
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when providerId is null then 1=1 else ad."ProviderId"=providerId end  	and
		adr."ReceiptTypeId"=1  and adr."Active"<>false  and adr."AdmissionId" is not null
AND CASE WHEN ("locationId" IS NULL OR "locationId"=0) THEN 1=1 ELSE ad."LocationId"="locationId" END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	
	)a
	group by  a."ProviderId"	
)

,refadmissionamount as (
	select a."ProviderId" , sum(A."CashTotal") "AdmissionRefCashTotal",sum(A."CardTotal") "AdmissionRefCardTotal",
	sum(A."UPITotal") "AdmissionRefUPITotal",sum(A."OnlineTotal") "AdmissionRefOnlineTotal",
	sum(A."ChequeTotal") "AdmissionRefChequeTotal",sum(A."PaytmTotal") "AdmissionRefPaytmTotal",
    
    sum(A."OtherTotal") "AdmissionRefOtherTotal",    
    sum(A."CardsSwipeTotal") "AdmissionRefCardsSwipeTotal",
    sum(A."CardStandAloneTotal") "AdmissionRefCardStandAloneTotal",
    sum(A."CardUPITotal") "AdmissionRefCardUPITotal",
    sum(A."CardsGPayTotal") "AdmissionRefCardsGPayTotal",
    sum(A."CashCashDrawerTotal") "AdmissionRefCashDrawer",
    sum(A."CashChequeTotal") "AdmissionRefCashChequeTotal",
    sum(A."CashDDTotal") "AdmissionRefCashDDTotal",
    sum(A."WalletPaytmOfflineTotal") "AdmissionRefWalletPaytmOfflineTotal",
    sum(A."WalletPhonePeOfflineTotal") "AdmissionRefWalletPhonePeOfflineTotal",
    sum(A."CashRemoteDepositTotal") "AdmissionRefCashRemoteDepositTotal",
    sum(A."WalletPaytmDQRTotal") "AdmissionRefWalletPaytmDQRTotal",
    
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal") + sum(A."ChequeTotal")+ sum(A."PaytmTotal")+
    
    sum(A."OtherTotal")+sum(A."CardsSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardsGPayTotal")+ 
    sum(A."CashCashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+ 
    sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal") "AdmissionRefAmount" 
	from (
select ad."ProviderId" "ProviderId"  ,  
		case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
        case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal" ,
		case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
        case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal" ,
		case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
        case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal" ,
        
       case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end "OtherTotal",
   case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardsSwipeTotal",
   case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end "CardStandAloneTotal" ,
   case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal" ,
   case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end "CardsGPayTotal",
   case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end "CashCashDrawerTotal",
   case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
   case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
   case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end "WalletPaytmOfflineTotal",
   case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end "WalletPhonePeOfflineTotal" ,
   case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end "CashRemoteDepositTotal",
   case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end "WalletPaytmDQRTotal"        
             
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false and adr."ReceiptAreaTypeId"=13
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when providerId is null then 1=1 else ad."ProviderId"=providerId end  and 
		adr."IsRefunded" = true   and adr."Active"<>false  and adr."AdmissionId" is not null
AND CASE WHEN ("locationId" IS NULL OR "locationId"=0) THEN 1=1 ELSE ad."LocationId"="locationId" END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	
	)a
	group by  a."ProviderId"	
)
,admissionamount as (
select A."ProviderId" ,
	coalesce(A."AdmissionCashTotal",0) - coalesce(B."AdmissionRefCashTotal",0) "AdmissionCashTotal",
	coalesce(A."AdmissionCardTotal",0) - coalesce(B."AdmissionRefCardTotal",0) "AdmissionCardTotal",
	coalesce(A."AdmissionUPITotal",0) - coalesce(B."AdmissionRefUPITotal",0) "AdmissionUPITotal",
	coalesce(A."AdmissionOnlineTotal",0) - coalesce(B."AdmissionRefOnlineTotal",0) "AdmissionOnlineTotal",
	coalesce(A."AdmissionChequeTotal",0) - coalesce(B."AdmissionRefChequeTotal",0) "AdmissionChequeTotal",
	coalesce(A."AdmissionPaytmTotal",0) - coalesce(B."AdmissionRefPaytmTotal",0) "AdmissionPaytmTotal",

    coalesce(A."AdmissionOtherTotal", 0) -   coalesce(B."AdmissionRefOtherTotal", 0) "AdmissionOtherTotal",
    coalesce(A."AdmissionCardsSwipeTotal",0) - coalesce(B."AdmissionRefCardsSwipeTotal",0) "AdmissionCardsSwipeTotal",
    coalesce(A."AdmissionCardStandAloneTotal",0) - coalesce(B."AdmissionRefCardStandAloneTotal",0) "AdmissionCardStandAloneTotal",
    coalesce(A."AdmissionCardUPITotal",0)- coalesce(B."AdmissionRefCardUPITotal",0) "AdmissionCardUPITotal",
    coalesce(A."AdmissionCardsGPayTotal",0)- coalesce(B."AdmissionRefCardsGPayTotal",0) "AdmissionCardsGPayTotal",
    coalesce(A."AdmissionCashDrawer",0)- coalesce(B."AdmissionRefCashDrawer",0) "AdmissionCashDrawer",
    coalesce(A."AdmissionCashChequeTotal",0)- coalesce(B."AdmissionRefCashChequeTotal",0) "AdmissionCashChequeTotal",
    coalesce(A."AdmissionCashDDTotal",0)- coalesce(B."AdmissionRefCashDDTotal",0) "AdmissionCashDDTotal",
    coalesce(A."AdmissionWalletPaytmOfflineTotal",0)- coalesce(B."AdmissionRefWalletPaytmOfflineTotal",0) "AdmissionWalletPaytmOfflineTotal",
    coalesce(A."AdmissionWalletPhonePeOfflineTotal",0)- coalesce(B."AdmissionRefWalletPhonePeOfflineTotal",0) "AdmissionWalletPhonePeOfflineTotal",
    coalesce(A."AdmissionCashRemoteDepositTotal",0)- coalesce(B."AdmissionRefCashRemoteDepositTotal",0) "AdmissionCashRemoteDepositTotal",
    coalesce(A."AdmissionWalletPaytmDQRTotal",0)- coalesce(B."AdmissionRefWalletPaytmDQRTotal",0) "AdmissionWalletPaytmDQRTotal",
    
    coalesce(A."AdmissionAmount",0) - coalesce(B."AdmissionRefAmount",0) "AdmissionAmount"
    
   from actadmissionamount A
	left join refadmissionamount B on A."ProviderId"=B."ProviderId"	 
)

,LabAmount as ( 
select a."ProviderId",sum(a."Cash") "LabCash",sum(a."Card") "LabCard" ,
sum(a."UPI") "LabUPI",sum(a."Online") "LabOnline" ,
sum(a."Cheque") "LabCheque",sum(a."Paytm") "LabPaytm",
    
    sum(a."Other") "Other",sum (a."CardsSwipe") "CardsSwipe",sum(a."CardStandAlone") "CardStandAlone",sum(a."CardUPI") "CardUPI",
    sum(a."CardsGPay") "CardsGPay",sum(a."CashCashDrawer") "CashCashDrawer",sum(a."CashCheque") "CashCheque",
   sum(a."CashDD") "CashDD",sum(a."WalletPaytmOffline") "WalletPaytmOffline",sum(a."WalletPhonePeOffline") "WalletPhonePeOffline" ,
   sum(a."CashRemoteDeposit") "CashRemoteDeposit", sum(a."WalletPaytmDQR") "WalletPaytmDQR",    
    
--    select * from "PayType"
    sum(a."Cash")+sum(a."Card") +sum(a."UPI")+sum(a."Online")+sum(a."Cheque")+sum(a."Paytm")+
    
    sum(a."Other")+sum(a."CardsSwipe")+sum(a."CardStandAlone")+sum(a."CardUPI")+sum(a."CardsGPay")+sum(a."CashCashDrawer")+
    sum(a."CashCheque")+sum(a."CashDD") +sum(a."WalletPaytmOffline")+sum(a."WalletPhonePeOffline")+
   sum(a."CashRemoteDeposit") +sum(a."WalletPaytmDQR") "LabAmount"  
from(
select 	a."ProviderId",							  
	case when ar."PayTypeId"=1 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."OverallNetAmount",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."OverallNetAmount",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."OverallNetAmount",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."OverallNetAmount",0) else 0 end "Paytm",
    
    case when ar."PayTypeId"=8 then coalesce(ar."OverallNetAmount",0) else 0 end "Other",
   case when ar."PayTypeId"=9 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardsSwipe",
   case when ar."PayTypeId"=10 then coalesce(ar."OverallNetAmount",0) else 0 end "CardStandAlone" ,
   case when ar."PayTypeId"=11 then coalesce(ar."OverallNetAmount",0) else 0 end "CardUPI" ,
   case when ar."PayTypeId"=12 then coalesce(ar."OverallNetAmount",0) else 0 end "CardsGPay",
   case when ar."PayTypeId"=13 then coalesce(ar."OverallNetAmount",0) else 0 end "CashCashDrawer",
   case when ar."PayTypeId"=14 then coalesce(ar."OverallNetAmount",0) else 0 end "CashCheque",
   case when ar."PayTypeId"=15 then coalesce(ar."OverallNetAmount",0) else 0 end "CashDD",
   case when ar."PayTypeId"=16 then coalesce(ar."OverallNetAmount",0) else 0 end "WalletPaytmOffline",
   case when ar."PayTypeId"=17 then coalesce(ar."OverallNetAmount",0) else 0 end "WalletPhonePeOffline" ,
   case when ar."PayTypeId"=18 then coalesce(ar."OverallNetAmount",0) else 0 end "CashRemoteDeposit",
   case when ar."PayTypeId"=19 then coalesce(ar."OverallNetAmount",0) else 0 end "WalletPaytmDQR" 
    
from "Provider" a
join "NewLabBookingHeader" ar on ar."DoctorId"=a."ProviderId" and ar."Active" <> false

 where case when providerId is null then 1=1 else a."ProviderId"=providerId end
AND CASE WHEN ("locationId" IS NULL OR "locationId"=0) THEN 1=1 ELSE ar."LocationId"="locationId" END    
	and case when "fromDate" is null then 1=1 
	else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end
)a
group by a."ProviderId" )

, PharmaSaleAmount as (	
select a."ProviderId", sum(a."Cash") "PharmaSaleCash",sum(a."Card") "PharmaSaleCard"
	,sum(a."UPI") "PharmaSaleUPI",sum(a."Online") "PharmaSaleOnline"
	,sum(a."Cheque") "PharmaSaleCheque",sum(a."Paytm") "PharmaSalePaytm",
    
    sum(a."Other") "PharmaSaleOther",sum (a."Cards Swipe") "PharmaSaleCardsSwipe",sum(a."Card StandAlone") "PharmaSaleCardStandAlone",
    sum(a."Card UPI") "PharmaSaleCardUPI",sum(a."Cards GPay") "PharmaSaleCardsGPay",sum(a."Cash CashDrawer") "PharmaSaleCashCashDrawer",
    sum(a."Cash Cheque") "PharmaSaleCashCheque",sum(a."Cash DD") "PharmaSaleCashDD",sum(a."Wallet Paytm Offline") "PharmaSaleWalletPaytmOffline",
    sum(a."Wallet PhonePe Offline") "PharmaSaleWalletPhonePeOffline",sum(a."Cash Remote Deposit") "PharmaSaleCashRemoteDeposit", 
    sum(a."Wallet Paytm DQR") "PharmaSaleWalletPaytmDQR", 
    
	 sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm") +
    
     sum(a."Other")+sum(a."Cards Swipe")+sum(a."Card StandAlone")+sum(a."Card UPI") +sum(a."Cards GPay")+sum(a."Cash CashDrawer")+
     sum(a."Cash Cheque")+sum(a."Cash DD")+sum(a."Wallet Paytm Offline")+sum(a."Wallet PhonePe Offline")+
     sum(a."Cash Remote Deposit")+sum(a."Wallet Paytm DQR") "PharmaSaleAmount" 
	from (
select a."ProviderId", 
	 case when ar."PayTypeId"=1 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."OverallNetAmount",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."OverallNetAmount",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."OverallNetAmount",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."OverallNetAmount",0) else 0 end "Paytm",
        
       case when ar."PayTypeId"=8 then coalesce(ar."OverallNetAmount",0) else 0 end "Other",
   case when ar."PayTypeId"=9 then coalesce(ar."OverallNetAmount",0) else 0 end  "Cards Swipe",
   case when ar."PayTypeId"=10 then coalesce(ar."OverallNetAmount",0) else 0 end "Card StandAlone" ,
   case when ar."PayTypeId"=11 then coalesce(ar."OverallNetAmount",0) else 0 end "Card UPI" ,
   case when ar."PayTypeId"=12 then coalesce(ar."OverallNetAmount",0) else 0 end "Cards GPay",
   case when ar."PayTypeId"=13 then coalesce(ar."OverallNetAmount",0) else 0 end "Cash CashDrawer",
   case when ar."PayTypeId"=14 then coalesce(ar."OverallNetAmount",0) else 0 end "Cash Cheque",
   case when ar."PayTypeId"=15 then coalesce(ar."OverallNetAmount",0) else 0 end "Cash DD",
   case when ar."PayTypeId"=16 then coalesce(ar."OverallNetAmount",0) else 0 end "Wallet Paytm Offline",
   case when ar."PayTypeId"=17 then coalesce(ar."OverallNetAmount",0) else 0 end "Wallet PhonePe Offline" ,
   case when ar."PayTypeId"=18 then coalesce(ar."OverallNetAmount",0) else 0 end "Cash Remote Deposit",
   case when ar."PayTypeId"=19 then coalesce(ar."OverallNetAmount",0) else 0 end "Wallet Paytm DQR" 
        
        
from "Provider" a
join "PharmacySaleHeader" ar on ar."ProviderId"=a."ProviderId"
where case when providerId is null then 1=1 else a."ProviderId"=providerId end 
AND CASE WHEN ("locationId" IS NULL OR "locationId"=0) THEN 1=1 ELSE ar."LocationId"="locationId" END 
and case when "fromDate" is null then 1=1 
else (ar."SaleDate"::date >= "fromDate" and ar."SaleDate"::date <= "toDate")  end	
	)a
group by a."ProviderId"
)

,PharmaReturnAmount as (
select a."ProviderId", sum(a."Cash") "PharmaReturnCash",sum(a."Card") "PharmaReturnCard" 
	,sum(a."UPI") "PharmaReturnUPI",sum(a."Online") "PharmaReturnOnline" 
	,sum(a."Cheque") "PharmaReturnCheque",sum(a."Paytm") "PharmaReturnPaytm" ,
    
     sum(a."Other") "PharmaReturnOther",sum (a."Cards Swipe") "PharmaReturnCardsSwipe",sum(a."Card StandAlone") "PharmaReturnCardStandAlone",
    sum(a."Card UPI") "PharmaReturnCardUPI",sum(a."Cards GPay") "PharmaReturnCardsGPay",sum(a."Cash CashDrawer") "PharmaReturnCashCashDrawer",
    sum(a."Cash Cheque") "PharmaReturnCashCheque",sum(a."Cash DD") "PharmaReturnCashDD",sum(a."Wallet Paytm Offline") "PharmaReturnWalletPaytmOffline",
    sum(a."Wallet PhonePe Offline") "PharmaReturnWalletPhonePeOffline",sum(a."Cash Remote Deposit") "PharmaReturnCashRemoteDeposit", 
    sum(a."Wallet Paytm DQR") "PharmaReturnWalletPaytmDQR", 
    
	sum(a."Cash")+sum(a."Card")+sum(a."UPI")+sum(a."Online")+sum(a."Cheque")+sum(a."Paytm") +
    
    sum(a."Other")+sum(a."Cards Swipe")+sum(a."Card StandAlone")+sum(a."Card UPI")+sum(a."Cards GPay")+sum(a."Cash CashDrawer")+
    sum(a."Cash Cheque") +sum(a."Cash DD")+sum(a."Wallet Paytm Offline")+sum(a."Wallet PhonePe Offline") +
   sum(a."Cash Remote Deposit")+sum(a."Wallet Paytm DQR") "PharmaReturnAmount" 
	from(
select a."ProviderId", 
	case when ar."PayTypeId"=1 then  coalesce(srh."OverallNetAmount",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(srh."OverallNetAmount",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(srh."OverallNetAmount",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(srh."OverallNetAmount",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(srh."OverallNetAmount",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(srh."OverallNetAmount",0) else 0 end "Paytm",
        
        case when ar."PayTypeId"=8 then coalesce(srh."OverallNetAmount",0) else 0 end "Other",
   case when ar."PayTypeId"=9 then coalesce(srh."OverallNetAmount",0) else 0 end  "Cards Swipe",
   case when ar."PayTypeId"=10 then coalesce(srh."OverallNetAmount",0) else 0 end "Card StandAlone" ,
   case when ar."PayTypeId"=11 then coalesce(srh."OverallNetAmount",0) else 0 end "Card UPI" ,
   case when ar."PayTypeId"=12 then coalesce(srh."OverallNetAmount",0) else 0 end "Cards GPay",
   case when ar."PayTypeId"=13 then coalesce(srh."OverallNetAmount",0) else 0 end "Cash CashDrawer",
   case when ar."PayTypeId"=14 then coalesce(srh."OverallNetAmount",0) else 0 end "Cash Cheque",
   case when ar."PayTypeId"=15 then coalesce(srh."OverallNetAmount",0) else 0 end "Cash DD",
   case when ar."PayTypeId"=16 then coalesce(srh."OverallNetAmount",0) else 0 end "Wallet Paytm Offline",
   case when ar."PayTypeId"=17 then coalesce(srh."OverallNetAmount",0) else 0 end "Wallet PhonePe Offline" ,
   case when ar."PayTypeId"=18 then coalesce(srh."OverallNetAmount",0) else 0 end "Cash Remote Deposit",
   case when ar."PayTypeId"=19 then coalesce(srh."OverallNetAmount",0) else 0 end "Wallet Paytm DQR" 
        
from "Provider" a
join "PharmacySaleHeader" ar on ar."ProviderId"=a."ProviderId"
left join "SaleReturnHeader" srh on srh."PharmacySaleHeaderId" = ar."PharmacySaleHeaderId"
where case when providerId is null then 1=1 else a."ProviderId"=providerId end  
AND CASE WHEN ("locationId" IS NULL OR "locationId"=0) THEN 1=1 ELSE ar."LocationId"="locationId" END 
and case when "fromDate" is null then 1=1 
else (srh."ReturnDate"::date >= "fromDate" and srh."ReturnDate"::date <= "toDate")  end	
	)a
group by a."ProviderId"
)

,PharmaAmount as (
select a."ProviderId", 
	
	 coalesce(a."PharmaSaleCash",0) - coalesce(b. "PharmaReturnCash",0) as  "PharmaSaleCash" ,
	 coalesce(a."PharmaSaleCard",0) - coalesce(b. "PharmaReturnCard",0) as  "PharmaSaleCard" ,
	 coalesce(a."PharmaSaleUPI",0) - coalesce(b. "PharmaReturnUPI",0) as  "PharmaSaleUPI" ,
	 coalesce(a."PharmaSaleOnline",0) - coalesce(b. "PharmaReturnOnline",0) as  "PharmaSaleOnline" ,
	 coalesce(a."PharmaSaleCheque",0) - coalesce(b. "PharmaReturnCheque",0) as  "PharmaSaleCheque" ,
	 coalesce(a."PharmaSalePaytm",0) - coalesce(b. "PharmaReturnPaytm",0) as  "PharmaSalePaytm" ,
	coalesce(a."PharmaSaleAmount",0) - coalesce(b. "PharmaReturnAmount",0) as  "PharmaAmount" ,
    
    coalesce(a."PharmaSaleOther",0) - coalesce(b. "PharmaReturnOther",0) as  "PharmaSaleOther" ,
	 coalesce(a."PharmaSaleCardsSwipe",0) - coalesce(b. "PharmaReturnCardsSwipe",0) as  "PharmaSaleCardsSwipe" ,
	 coalesce(a."PharmaSaleCardStandAlone",0) - coalesce(b. "PharmaReturnCardStandAlone",0) as  "PharmaSaleCardStandAlone" ,
	 coalesce(a."PharmaSaleCardUPI",0) - coalesce(b. "PharmaReturnCardUPI",0) as  "PharmaSaleCardUPI" ,
	 coalesce(a."PharmaSaleCardsGPay",0) - coalesce(b. "PharmaReturnCardsGPay",0) as  "PharmaSaleCardsGPay" ,
	 coalesce(a."PharmaSaleCashCashDrawer",0) - coalesce(b. "PharmaReturnCashCashDrawer",0) as  "PharmaSaleCashCashDrawer" ,     
     coalesce(a."PharmaSaleCashCheque",0) - coalesce(b. "PharmaReturnCashCheque",0) as  "PharmaSaleCashCheque" ,
	 coalesce(a."PharmaSaleCashDD",0) - coalesce(b. "PharmaReturnCashDD",0) as  "PharmaSaleCashDD" ,
	 coalesce(a."PharmaSaleWalletPaytmOffline",0) - coalesce(b. "PharmaReturnWalletPaytmOffline",0) as  "PharmaSaleWalletPaytmOffline" ,
	 coalesce(a."PharmaSaleWalletPhonePeOffline",0) - coalesce(b. "PharmaReturnWalletPhonePeOffline",0) as  "PharmaSaleWalletPhonePeOffline" ,
	 coalesce(a."PharmaSaleCashRemoteDeposit",0) - coalesce(b. "PharmaReturnCashRemoteDeposit",0) as  "PharmaSaleCashRemoteDeposit" ,
	 coalesce(a."PharmaSaleWalletPaytmDQR",0) - coalesce(b. "PharmaReturnWalletPaytmDQR",0) as  "PharmaSaleWalletPaytmDQR" 
    
from PharmaSaleAmount a
	left join PharmaReturnAmount b on a."ProviderId"=b."ProviderId"
)
	
select distinct  a."ProviderId",a."DoctorName"::text "DoctorName",
						  ap."AppointmentCashTotal",ap."AppointmentCardTotal",ap."AppointmentUPITotal",ap."AppointmentOnlineTotal", ap."AppointmentChequeTotal",
                          ap."AppointmentPaytmTotal", 
                          
                         ap."AppointmentOtherTotal",ap."AppointmentCardsSwipeTotal",ap."AppointmentCardStandAloneTotal",ap."AppointmentCardUPITotal",
                         ap."AppointmentCardsGPayTotal",ap."AppointmentCashDrawerTotal",ap. "AppointmentCashChequeTotal",ap. "AppointmentCashDDTotal",
                         ap."AppointmentWalletPaytmOfflineTotal",ap."AppointmentWalletPhonePeOfflineTotal", ap."AppointmentCashRemoteDepositTotal",
                         ap."AppointmentWalletPaytmDQRTotal", ap."AppointmentAmount",
                        --  select* from "PayType"
						  ad."AdmissionCashTotal",ad."AdmissionCardTotal",ad."AdmissionUPITotal",ad."AdmissionOnlineTotal", ad."AdmissionChequeTotal",ad."AdmissionPaytmTotal",
                         ad."AdmissionOtherTotal",ad."AdmissionCardsSwipeTotal",ad."AdmissionCardStandAloneTotal",ad."AdmissionCardUPITotal",
                         ad."AdmissionCardsGPayTotal",ad."AdmissionCashDrawer",ad."AdmissionCashChequeTotal",ad. "AdmissionCashDDTotal",
                         ad."AdmissionWalletPaytmOfflineTotal",ad. "AdmissionWalletPhonePeOfflineTotal",ad. "AdmissionCashRemoteDepositTotal",
                         ad."AdmissionWalletPaytmDQRTotal",ad."AdmissionAmount",
                          
						 lb."LabCash", lb."LabCard",lb."LabUPI", lb."LabOnline",lb."LabCheque", lb."LabPaytm",
                         lb."Other",lb."CardsSwipe",lb."CardStandAlone",lb."CardUPI",lb."CardsGPay",lb."CashCashDrawer",lb."CashCheque",lb."CashDD",
                         lb."WalletPaytmOffline",lb."WalletPhonePeOffline",lb."CashRemoteDeposit",lb."WalletPaytmDQR",
                          lb."LabAmount",
                          
sum(pa."PharmaSaleCash") over(partition by a."ProviderId")  "PharmacySaleCash",
sum(pa."PharmaSaleCard") over(partition by a."ProviderId") 	"PharmacySaleCard",
sum(pa."PharmaSaleUPI") over(partition by a."ProviderId")  "PharmacySaleUPI",
sum(pa."PharmaSaleOnline") over(partition by a."ProviderId") 	"PharmacySaleOnline",
sum(pa."PharmaSaleCheque") over(partition by a."ProviderId")  "PharmacySaleCheque",
sum(pa."PharmaSalePaytm") over(partition by a."ProviderId") 	"PharmacySalePaytm",

sum(pa."PharmaSaleOther") over(partition by a."ProviderId")  "PharmacySaleOther",
sum(pa."PharmaSaleCardsSwipe") over(partition by a."ProviderId") 	"PharmacySaleCardsSwipe",
sum(pa."PharmaSaleCardStandAlone") over(partition by a."ProviderId")  "PharmacySaleCardStandAlone",
sum(pa."PharmaSaleCardUPI") over(partition by a."ProviderId") 	"PharmacySaleCardUPI",
sum(pa."PharmaSaleCardsGPay") over(partition by a."ProviderId")  "PharmacySaleCardsGPay",
sum(pa."PharmaSaleCashCashDrawer") over(partition by a."ProviderId") 	"PharmacySaleCashCashDrawer",
sum(pa."PharmaSaleCashCheque") over(partition by a."ProviderId")  "PharmacySaleCashCheque",
sum(pa."PharmaSaleCashDD") over(partition by a."ProviderId") 	"PharmacySaleCashDD",
sum(pa."PharmaSaleWalletPaytmOffline") over(partition by a."ProviderId")  "PharmacySaleWalletPaytmOffline",
sum(pa."PharmaSaleWalletPhonePeOffline") over(partition by a."ProviderId") 	"PharmacySaleWalletPhonePeOffline",
sum(pa."PharmaSaleCashRemoteDeposit") over(partition by a."ProviderId")  "PharmacySaleCashRemoteDeposit",
sum(pa."PharmaSaleWalletPaytmDQR") over(partition by a."ProviderId") 	"PharmacySaleWalletPaytmDQR",

sum(pa."PharmaAmount") over(partition by a."ProviderId") "PharmacyAmount",
coalesce(ap."AppointmentCashTotal",0)+	coalesce(ad."AdmissionCashTotal",0)+coalesce(lb."LabCash",0)+coalesce(sum(pa."PharmaSaleCash") over(partition by a."ProviderId") ,0) "TotalCash",
coalesce(ap."AppointmentCardTotal",0)+	coalesce(ad."AdmissionCardTotal",0)+coalesce(lb."LabCard",0)+coalesce(sum(pa."PharmaSaleCard") over(partition by a."ProviderId"),0)  "TotalCard",	
coalesce(ap."AppointmentUPITotal",0)+	coalesce(ad."AdmissionUPITotal",0)+coalesce(lb."LabUPI",0)+coalesce(sum(pa."PharmaSaleUPI") over(partition by a."ProviderId") ,0) "TotalUPI",
coalesce(ap."AppointmentOnlineTotal",0)+	coalesce(ad."AdmissionOnlineTotal",0)+coalesce(lb."LabOnline",0)+coalesce(sum(pa."PharmaSaleOnline") over(partition by a."ProviderId"),0)  "TotalOnline",	
coalesce(ap."AppointmentChequeTotal",0)+	coalesce(ad."AdmissionChequeTotal",0)+coalesce(lb."LabCheque",0)+coalesce(sum(pa."PharmaSaleCheque") over(partition by a."ProviderId") ,0) "TotalCheque",
coalesce(ap."AppointmentPaytmTotal",0)+	coalesce(ad."AdmissionPaytmTotal",0)+coalesce(lb."LabPaytm",0)+coalesce(sum(pa."PharmaSalePaytm") over(partition by a."ProviderId"),0)  "TotalPaytm",	

coalesce(ap."AppointmentOtherTotal",0)+ coalesce(ad."AdmissionOtherTotal", 0) +coalesce(lb."Other",0)+coalesce(sum(pa."PharmaSaleOther") over(partition by a."ProviderId"),0) as "OtherTotal",
coalesce(ap."AppointmentCardsSwipeTotal",0)+coalesce(ad."AdmissionCardsSwipeTotal",0)+coalesce(lb."CardsSwipe",0) +coalesce(sum(pa."PharmaSaleCardsSwipe") over(partition by a."ProviderId"),0)as "CardsSwipeTotal",
coalesce(ap."AppointmentCardStandAloneTotal",0)+coalesce(ad."AdmissionCardStandAloneTotal",0)+coalesce(lb."CardStandAlone",0)+coalesce(sum(pa."PharmaSaleCardStandAlone") over(partition by a."ProviderId"),0) as "CardStandAloneTotal",
coalesce(ap."AppointmentCardUPITotal",0)+coalesce(ad."AdmissionCardUPITotal")+coalesce(lb."CardUPI",0)+coalesce(sum(pa."PharmaSaleCardUPI") over(partition by a."ProviderId") ,0) as "CardUPITotal",
coalesce(ap."AppointmentCardsGPayTotal",0)+ coalesce(ad."AdmissionCardsGPayTotal",0) +coalesce(lb."CardsGPay",0)+coalesce(sum(pa."PharmaSaleCardsGPay") over(partition by a."ProviderId") ,0) as "CardsGPayTotal",
coalesce(ap."AppointmentCashDrawerTotal",0)+coalesce(ad."AdmissionCashDrawer",0)+coalesce(lb."CashCashDrawer",0)+coalesce(sum(pa."PharmaSaleCashCheque") over(partition by a."ProviderId"),0) as "CashDrawer",
coalesce(ap."AppointmentCashChequeTotal",0)+coalesce(ad."AdmissionCashChequeTotal",0)+coalesce(lb."CashCheque",0)+coalesce(sum(pa."PharmaSaleCashCheque") over(partition by a."ProviderId") ,0) as "CashChequeTotal",
coalesce(ap."AppointmentCashDDTotal",0)+coalesce(ad."AdmissionCashDDTotal",0)+coalesce(lb."CashDD",0)+coalesce(sum(pa."PharmaSaleCashDD") over(partition by a."ProviderId"),0) as "CashDDTotal",
coalesce(ap."AppointmentWalletPaytmOfflineTotal",0)+coalesce(ad."AdmissionWalletPaytmOfflineTotal",0)+ coalesce(lb."WalletPaytmOffline",0)+coalesce(sum(pa."PharmaSaleWalletPaytmOffline") over(partition by a."ProviderId"),0) as "WalletPaytmOfflineTotal",
coalesce(ap."AppointmentWalletPhonePeOfflineTotal",0)+coalesce(ad."AdmissionWalletPhonePeOfflineTotal",0)+ coalesce(lb."WalletPhonePeOffline",0)+coalesce(sum(pa."PharmaSaleWalletPhonePeOffline") over(partition by a."ProviderId"),0) as "WalletPhonePeOfflineTotal",
coalesce(ap."AppointmentCashRemoteDepositTotal",0)+coalesce(ad."AdmissionCashRemoteDepositTotal",0)+coalesce(lb."CashRemoteDeposit",0)+coalesce(sum(pa."PharmaSaleCashRemoteDeposit") over(partition by a."ProviderId"),0) as "CashRemoteDepositTotal",
coalesce(ap."AppointmentWalletPaytmDQRTotal",0)+coalesce(ad."AdmissionWalletPaytmDQRTotal",0)+coalesce(lb."WalletPaytmDQR",0)+coalesce(sum(pa."PharmaSaleWalletPaytmDQR") over(partition by a."ProviderId") ,0)  as "WalletPaytmDQRTotal",      

coalesce(ap."AppointmentAmount",0)+coalesce(ad."AdmissionAmount",0)+coalesce(lb."LabAmount",0)+coalesce(sum(pa."PharmaAmount") over(partition by a."ProviderId"),0) "Total"

from accountdata a

left join appointmentamount ap on ap."ProviderId"=a."ProviderId"
left join admissionamount ad on ad."ProviderId"=a."ProviderId"
left join LabAmount lb on lb."ProviderId"=a."ProviderId"
left join PharmaAmount pa on pa."ProviderId"=a."ProviderId"
;
	end
$BODY$;
-------------------------------------------------------------------------------------
DROP FUNCTION IF EXISTS public.udf_emloyee_new_revenue(integer, integer, integer, date, date);

CREATE OR REPLACE FUNCTION public.udf_emloyee_new_revenue(
	accountid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer,
	roleid integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date)
    RETURNS TABLE("AccountId" integer, "EmployeeName" text, "RoleName" character varying, "RegistrationCashTotal" numeric, "RegistrationCardTotal" numeric, "RegistrationUPITotal" numeric, "RegistrationOnlineTotal" numeric, "RegistrationChequeTotal" numeric, "RegistrationPaytmTotal" numeric, "RegistrationNotPaidTotal" numeric, "RegistrationOtherTotal" numeric, "RegistrationCardSwipeTotal" numeric, "RegistrationCardStandAloneTotal" numeric, "RegistrationCardUPITotal" numeric, "RegistrationCardGpayTotal" numeric, "RegistrationCashDrawerTotal" numeric, "RegistrationCashChequeTotal" numeric, "RegistrationCashDDTotal" numeric, "RegistrationWalletPaytmOfflineTotal" numeric, "RegistrationWalletPhonePeOfflineTotal" numeric, "RegistrationCashRemoteDepositTotal" numeric, "RegistrationWalletPaytmDQRTotal" numeric, registrationamount numeric, "AppointmentCashTotal" numeric, "AppointmentCardTotal" numeric, "AppointmentUPITotal" numeric, "AppointmentOnlineTotal" numeric, "AppointmentChequeTotal" numeric, "AppointmentPaytmTotal" numeric, "AppointmentNotPaidTotal" numeric, "AppointmentOtherTotal" numeric, "AppointmentCardSwipeTotal" numeric, "AppointmentCardStandAloneTotal" numeric, "AppointmentCardUPITotal" numeric, "AppointmentCardGpayTotal" numeric, "AppointmentCashDrawerTotal" numeric, "AppointmentCashChequeTotal" numeric, "AppointmentCashDDTotal" numeric, "AppointmentWalletPaytmOfflineTotal" numeric, "AppointmentWalletPhonePeOfflineTotal" numeric, "AppointmentCashRemoteDepositTotal" numeric, "AppointmentWalletPaytmDQRTotal" numeric, "AppointmentAmount" numeric, "AdmissionCashTotal" numeric, "AdmissionCardTotal" numeric, "AdmissionUPITotal" numeric, "AdmissionOnlineTotal" numeric, "AdmissionChequeTotal" numeric, "AdmissionPaytmTotal" numeric, "AdmissionNotPaidTotal" numeric, "AdmissionOtherTotal" numeric, "AdmissionCardSwipeTotal" numeric, "AdmissionCardStandAloneTotal" numeric, "AdmissionCardUPITotal" numeric, "AdmissionCardGpayTotal" numeric, "AdmissionCashDrawerTotal" numeric, "AdmissionCashChequeTotal" numeric, "AdmissionCashDDTotal" numeric, "AdmissionWalletPaytmOfflineTotal" numeric, "AdmissionWalletPhonePeOfflineTotal" numeric, "AdmissionCashRemoteDepositTotal" numeric, "AdmissionWalletPaytmDQRTotal" numeric, "AdmissionAmount" numeric, "LabCash" numeric, "LabCard" numeric, "LabUPI" numeric, "LabOnline" numeric, "LabCheque" numeric, "LabPaytm" numeric, "LabNotPaidTotal" numeric, "LabOtherTotal" numeric, "LabCardSwipeTotal" numeric, "LabCardStandAloneTotal" numeric, "LabCardUPITotal" numeric, "LabCardGpayTotal" numeric, "LabCashDrawerTotal" numeric, "LabCashChequeTotal" numeric, "LabCashDDTotal" numeric, "LabWalletPaytmOfflineTotal" numeric, "LabWalletPhonePeOfflineTotal" numeric, "LabCashRemoteDepositTotal" numeric, "LabWalletPaytmDQRTotal" numeric, "LabAmount" numeric, "PharmacySaleCash" numeric, "PharmacySaleCard" numeric, "PharmacySaleUPI" numeric, "PharmacySaleOnline" numeric, "PharmacySaleCheque" numeric, "PharmacySalePaytm" numeric, "PharmacySaleNotPaidTotal" numeric, "PharmacySaleOtherTotal" numeric, "PharmacySaleCardSwipeTotal" numeric, "PharmacySaleCardStandAloneTotal" numeric, "PharmacySaleCardUPITotal" numeric, "PharmacySaleCardGpayTotal" numeric, "PharmacySaleCashDrawerTotal" numeric, "PharmacySaleCashChequeTotal" numeric, "PharmacySaleCashDDTotal" numeric, "PharmacySaleWalletPaytmOfflineTotal" numeric, "PharmacySaleWalletPhonePeOfflineTotal" numeric, "PharmacySaleCashRemoteDepositTotal" numeric, "PharmacySaleWalletPaytmDQRTotal" numeric, "PharmacyAmount" numeric, "TotalCash" numeric, "TotalCard" numeric, "TotalUPI" numeric, "TotalOnline" numeric, "TotalCheque" numeric, "TotalPaytm" numeric, "NotPaidTotal" numeric, "OtherTotal" numeric, "CardSwipeTotal" numeric, "CardStandAloneTotal" numeric, "CardUPITotal" numeric, "CardGpayTotal" numeric, "CashDrawerTotal" numeric, "CashChequeTotal" numeric, "CashDDTotal" numeric, "WalletPaytmOfflineTotal" numeric, "WalletPhonePeOfflineTotal" numeric, "CashRemoteDepositTotal" numeric, "WalletPaytmDQRTotal" numeric, "Total" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
 return query 

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"  
join "Role" rol on rol."RoleId" = a."RoleId" --and lower(rol."RoleName") <> lower('Patient')
where a."RoleId"<>4
and	case when accountid is null then 1=1 else a."AccountId"=accountid end   
and	case when roleid is null then 1=1 else a."RoleId"=roleid end 	
AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE LAM."LocationId"=locationId END
)
,patientRegistrationamount as(
 select a."AccountId",
	sum(A."CashTotal") "RegistrationCashTotal"
	,sum(A."CardTotal") "RegistrationCardTotal",
 	sum(A."UPITotal") "RegistrationUPITotal",
	sum(A."OnlineTotal") "RegistrationOnlineTotal",
 	sum(A."ChequeTotal") "RegistrationChequeTotal",
	sum(A."PaytmTotal") "RegistrationPaytmTotal",
	sum(A."NotPaidTotal") "RegistrationNotPaidTotal",
	sum(A."OtherTotal") "RegistrationOtherTotal",
	sum(A."CardSwipeTotal") "RegistrationCardSwipeTotal",
	sum(A."CardStandAloneTotal") "RegistrationCardStandAloneTotal",
	sum(A."CardUPITotal") "RegistrationCardUPITotal",
	sum(A."CardGpayTotal") "RegistrationCardGpayTotal",
	sum(A."CashDrawerTotal") "RegistrationCashDrawerTotal",
	sum(A."CashChequeTotal") "RegistrationCashChequeTotal",
	sum(A."CashDDTotal") "RegistrationCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "RegistrationWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "RegistrationWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "RegistrationCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "RegistrationWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")
	+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
 	 
	registrationamount
 	from ( 
	select  a."CreatedBy"  "AccountId",   
   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
   case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal",
	case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
   case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
   case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
   case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
   case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"	
		from "Receipt" A
   join "Patient" p on  p."PatientId" =A."RespectiveId"   and A."ReceiptAreaTypeId"=3    
   where A."ReceiptTypeId"=1 and p."Active" <> false and A."Active"<>false and A."RespectiveId" is not null
		and case when accountid is null then 1=1 else a."CreatedBy"=accountid end  
		and case when (locationId IS NULL OR locationId=0) THEN 1=1 ELSE p."LocationId"=locationId END 
		and		case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end		
	) a group by  a."AccountId"	
)

,actappointmentamount as (
	
	select a."AccountId",
	sum(A."CashTotal") "AppointmentCashTotal",
	sum(A."CardTotal") "AppointmentCardTotal",
	sum(A."UPITotal") "AppointmentUPITotal",
	sum(A."OnlineTotal") "AppointmentOnlineTotal",
	sum(A."ChequeTotal") "AppointmentChequeTotal",
	sum(A."PaytmTotal") "AppointmentPaytmTotal",
	sum(A."NotPaidTotal") "AppointmentNotPaidTotal",
	sum(A."OtherTotal") "AppointmentOtherTotal",
	sum(A."CardSwipeTotal") "AppointmentCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AppointmentCardStandAloneTotal",
	sum(A."CardUPITotal") "AppointmentCardUPITotal",
	sum(A."CardGpayTotal") "AppointmentCardGpayTotal",
	sum(A."CashDrawerTotal") "AppointmentCashDrawerTotal",
	sum(A."CashChequeTotal") "AppointmentCashChequeTotal",
	sum(A."CashDDTotal") "AppointmentCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AppointmentWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AppointmentWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AppointmentCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AppointmentWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")
	+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	appointmentamount
	from (
   select  a."CreatedBy"  "AccountId",   
   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
   case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal",
	case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
    case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
	case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
    case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
    case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"	
	from "Receipt" A
    join "Appointment" ap on  ap."AppointmentId" =A."RespectiveId"   and A."ReceiptAreaTypeId"=4
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
    and ap."Active" =true	
   where case when accountid is null then 1=1 else a."CreatedBy"=accountid end  and A."ReceiptTypeId"=1 	
	and A."Active"<>false and A."RespectiveId" is not null
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
	and coalesce(A."IsRefunded",false) <>true and ap."Status" <> 'C' and	
	case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end	
	)a 
	group by  a."AccountId"	 
)

,refundappointmentamount as (
	select a."AccountId" ,
	sum(A."CashTotal") "AppointmentRefCashTotal",
	sum(A."CardTotal") "AppointmentRefCardTotal",
	sum(A."UPITotal") "AppointmentRefUPITotal",
	sum(A."OnlineTotal") "AppointmentRefOnlineTotal",
	sum(A."ChequeTotal") "AppointmentRefChequeTotal",
	sum(A."PaytmTotal") "AppointmentRefPaytmTotal",
	sum(A."NotPaidTotal") "AppointmentRefNotPaidTotal",
	sum(A."OtherTotal") "AppointmentRefOtherTotal",
	sum(A."CardSwipeTotal") "AppointmentRefCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AppointmentRefCardStandAloneTotal",
	sum(A."CardUPITotal") "AppointmentRefCardUPITotal",
	sum(A."CardGpayTotal") "AppointmentRefCardGpayTotal",
	sum(A."CashDrawerTotal") "AppointmentRefCashDrawerTotal",
	sum(A."CashChequeTotal") "AppointmentRefCashChequeTotal",
	sum(A."CashDDTotal") "AppointmentRefCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AppointmentRefWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AppointmentRefWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AppointmentRefCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AppointmentRefWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	
	 refappointmentamount 
	from (
    select  a."CreatedBy"  "AccountId",
	 case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
      case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal" ,
	 case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
     case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
	case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
    case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
   case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"
		 from "Receipt" A
    join "Appointment" ap on ap."AppointmentId" =A."RespectiveId" and A."ReceiptAreaTypeId"=5    
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
   and ap."Status" <> 'C'   and ap."Active" =true
	
   where case when accountid is null then 1=1 else a."CreatedBy"=accountid end   
	and A."Active"<>false and A."RespectiveId" is not null 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
	and coalesce(A."IsRefunded",false) = true and 
	case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end
	) a
	group by  a."AccountId"	
	
)

,appointmentamount as (
select  A."AccountId",
	coalesce(A."AppointmentCashTotal",0) - coalesce(B."AppointmentRefCashTotal",0) as "AppointmentCashTotal" ,
	coalesce(A."AppointmentCardTotal",0) - coalesce(B."AppointmentRefCardTotal",0) as "AppointmentCardTotal" ,
	coalesce(A."AppointmentUPITotal",0) - coalesce(B."AppointmentRefUPITotal",0) as "AppointmentUPITotal" ,
	coalesce(A."AppointmentOnlineTotal",0) - coalesce(B."AppointmentRefOnlineTotal",0) as "AppointmentOnlineTotal" ,
	coalesce(A."AppointmentChequeTotal",0) - coalesce(B."AppointmentRefChequeTotal",0) as "AppointmentChequeTotal" ,
	coalesce(A."AppointmentPaytmTotal",0) - coalesce(B."AppointmentRefPaytmTotal",0) as "AppointmentPaytmTotal" ,
	coalesce(A."AppointmentNotPaidTotal",0) - coalesce(B."AppointmentRefNotPaidTotal",0) as "AppointmentNotPaidTotal" ,
	coalesce(A."AppointmentOtherTotal",0) - coalesce(B."AppointmentRefOtherTotal",0) as "AppointmentOtherTotal" ,
	coalesce(A."AppointmentCardSwipeTotal",0) - coalesce(B."AppointmentRefCardSwipeTotal",0) as "AppointmentCardSwipeTotal" ,
	coalesce(A."AppointmentCardStandAloneTotal",0) - coalesce(B."AppointmentRefCardStandAloneTotal",0) as "AppointmentCardStandAloneTotal" ,
	coalesce(A."AppointmentCardUPITotal",0) - coalesce(B."AppointmentRefCardUPITotal",0) as "AppointmentCardUPITotal" ,
	coalesce(A."AppointmentCardGpayTotal",0) - coalesce(B."AppointmentRefCardGpayTotal",0) as "AppointmentCardGpayTotal" ,
	coalesce(A."AppointmentCashDrawerTotal",0) - coalesce(B."AppointmentRefCashDrawerTotal",0) as "AppointmentCashDrawerTotal" ,
	coalesce(A."AppointmentCashChequeTotal",0) - coalesce(B."AppointmentRefCashChequeTotal",0) as "AppointmentCashChequeTotal" ,
	coalesce(A."AppointmentCashDDTotal",0) - coalesce(B."AppointmentRefCashDDTotal",0) as "AppointmentCashDDTotal" ,
	coalesce(A."AppointmentWalletPaytmOfflineTotal",0) - coalesce(B."AppointmentRefWalletPaytmOfflineTotal",0) as "AppointmentWalletPaytmOfflineTotal" ,
	coalesce(A."AppointmentWalletPhonePeOfflineTotal",0) - coalesce(B."AppointmentRefWalletPhonePeOfflineTotal",0) as "AppointmentWalletPhonePeOfflineTotal" ,
	coalesce(A."AppointmentCashRemoteDepositTotal",0) - coalesce(B."AppointmentRefCashRemoteDepositTotal",0) as "AppointmentCashRemoteDepositTotal" ,
		coalesce(A."AppointmentWalletPaytmDQRTotal",0) - coalesce(B."AppointmentRefWalletPaytmDQRTotal",0) as "AppointmentWalletPaytmDQRTotal" ,
	coalesce(A.appointmentamount,0) - coalesce(B.refappointmentamount,0) as "AppointmentAmount" from actappointmentamount A
	left join refundappointmentamount B on A."AccountId"=B."AccountId"
	
	
)

,actadmissionamount as (
	
	select a."AccountId" , 
	sum(A."CashTotal") "AdmissionCashTotal",
	sum(A."CardTotal") "AdmissionCardTotal",
	 sum(A."UPITotal") "AdmissionUPITotal",
	sum(A."OnlineTotal") "AdmissionOnlineTotal",
	 sum(A."ChequeTotal") "AdmissionChequeTotal",
	sum(A."PaytmTotal") "AdmissionPaytmTotal",
	sum(A."NotPaidTotal") "AdmissionNotPaidTotal",
	sum(A."OtherTotal") "AdmissionOtherTotal",
	sum(A."CardSwipeTotal") "AdmissionCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AdmissionCardStandAloneTotal",
	sum(A."CardUPITotal") "AdmissionCardUPITotal",
	sum(A."CardGpayTotal") "AdmissionCardGpayTotal",
	sum(A."CashDrawerTotal") "AdmissionCashDrawerTotal",
	sum(A."CashChequeTotal") "AdmissionCashChequeTotal",
	sum(A."CashDDTotal") "AdmissionCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AdmissionWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AdmissionWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AdmissionCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AdmissionWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	"AdmissionAmount"
	from (
select adr."CreatedBy" "AccountId" ,
     case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
     case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal"	,
	  case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
       case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal"	,	
       case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
       case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal"	,
       case when adr."PayTypeId"=7 then coalesce(adr."Cost",0) else 0 end "NotPaidTotal",
        case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end  "OtherTotal",
        case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardSwipeTotal",
        case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end  "CardStandAloneTotal",
        case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal",
        case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end  "CardGpayTotal",
        case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end  "CashDrawerTotal",
        case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
        case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
        case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
        case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
        case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end  "CashRemoteDepositTotal",
        case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end   "WalletPaytmDQRTotal"
												  
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when accountid is null then 1=1 else adr."CreatedBy"=accountid end 	
	and adr."ReceiptTypeId"=1  and adr."Active"<>false  and adr."AdmissionId" is not null
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	)a
	group by  a."AccountId"	
)

,refadmissionamount as (
	select a."AccountId" , 
	sum(A."CashTotal") "AdmissionRefCashTotal",
	sum(A."CardTotal") "AdmissionRefCardTotal",
	sum(A."UPITotal") "AdmissionRefUPITotal",
	sum(A."OnlineTotal") "AdmissionRefOnlineTotal",
	sum(A."ChequeTotal") "AdmissionRefChequeTotal",
	sum(A."PaytmTotal") "AdmissionRefPaytmTotal",
	sum(A."NotPaidTotal") "AdmissionRefNotPaidTotal",
	sum(A."OtherTotal") "AdmissionRefOtherTotal",
	sum(A."CardSwipeTotal") "AdmissionRefCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AdmissionRefCardStandAloneTotal",
	sum(A."CardUPITotal") "AdmissionRefCardUPITotal",
	sum(A."CardGpayTotal") "AdmissionRefCardGpayTotal",
	sum(A."CashDrawerTotal") "AdmissionRefCashDrawerTotal",
	sum(A."CashChequeTotal") "AdmissionRefCashChequeTotal",
	sum(A."CashDDTotal") "AdmissionRefCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AdmissionRefWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AdmissionRefWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AdmissionRefCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AdmissionRefWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")

	"AdmissionRefAmount" 
	from (
select adr."CreatedBy" "AccountId"  ,  
		case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
        case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal" ,
		case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
        case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal" ,
		case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
        case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal" ,
		case when adr."PayTypeId"=7 then coalesce(adr."Cost",0) else 0 end "NotPaidTotal",
        case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end  "OtherTotal",
        case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardSwipeTotal",
        case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end  "CardStandAloneTotal",
        case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal",
        case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end  "CardGpayTotal",
        case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end  "CashDrawerTotal",
        case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
        case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
        case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
        case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
        case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end  "CashRemoteDepositTotal",
        case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end   "WalletPaytmDQRTotal"
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when accountid is null then 1=1 else adr."CreatedBy"=accountid end 	
	 and adr."IsRefunded" = true   and adr."Active"<>false  and adr."AdmissionId" is not null
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	)a
	group by  a."AccountId"	
)

,admissionamount as (
select A."AccountId" ,
	coalesce(A."AdmissionCashTotal",0) - coalesce(B."AdmissionRefCashTotal",0) "AdmissionCashTotal",
	coalesce(A."AdmissionCardTotal",0) - coalesce(B."AdmissionRefCardTotal",0) "AdmissionCardTotal",
	coalesce(A."AdmissionUPITotal",0) - coalesce(B."AdmissionRefUPITotal",0) "AdmissionUPITotal",
	coalesce(A."AdmissionOnlineTotal",0) - coalesce(B."AdmissionRefOnlineTotal",0) "AdmissionOnlineTotal",
	coalesce(A."AdmissionChequeTotal",0) - coalesce(B."AdmissionRefChequeTotal",0) "AdmissionChequeTotal",
	coalesce(A."AdmissionPaytmTotal",0) - coalesce(B."AdmissionRefPaytmTotal",0) "AdmissionPaytmTotal",
	coalesce(A."AdmissionNotPaidTotal",0) - coalesce(B."AdmissionRefNotPaidTotal",0) as "AdmissionNotPaidTotal" ,
	coalesce(A."AdmissionOtherTotal",0) - coalesce(B."AdmissionRefOtherTotal",0) as "AdmissionOtherTotal" ,
	coalesce(A."AdmissionCardSwipeTotal",0) - coalesce(B."AdmissionRefCardSwipeTotal",0) as "AdmissionCardSwipeTotal" ,
	coalesce(A."AdmissionCardStandAloneTotal",0) - coalesce(B."AdmissionRefCardStandAloneTotal",0) as "AdmissionCardStandAloneTotal" ,
	coalesce(A."AdmissionCardUPITotal",0) - coalesce(B."AdmissionRefCardUPITotal",0) as "AdmissionCardUPITotal" ,
	coalesce(A."AdmissionCardGpayTotal",0) - coalesce(B."AdmissionRefCardGpayTotal",0) as "AdmissionCardGpayTotal" ,
	coalesce(A."AdmissionCashDrawerTotal",0) - coalesce(B."AdmissionRefCashDrawerTotal",0) as "AdmissionCashDrawerTotal" ,
	coalesce(A."AdmissionCashChequeTotal",0) - coalesce(B."AdmissionRefCashChequeTotal",0) as "AdmissionCashChequeTotal" ,
	coalesce(A."AdmissionCashDDTotal",0) - coalesce(B."AdmissionRefCashDDTotal",0) as "AdmissionCashDDTotal" ,
	coalesce(A."AdmissionWalletPaytmOfflineTotal",0) - coalesce(B."AdmissionRefWalletPaytmOfflineTotal",0) as "AdmissionWalletPaytmOfflineTotal" ,
	coalesce(A."AdmissionWalletPhonePeOfflineTotal",0) - coalesce(B."AdmissionRefWalletPhonePeOfflineTotal",0) as "AdmissionWalletPhonePeOfflineTotal" ,
	coalesce(A."AdmissionCashRemoteDepositTotal",0) - coalesce(B."AdmissionRefCashRemoteDepositTotal",0) as "AdmissionCashRemoteDepositTotal" ,
		coalesce(A."AdmissionWalletPaytmDQRTotal",0) - coalesce(B."AdmissionRefWalletPaytmDQRTotal",0) as "AdmissionWalletPaytmDQRTotal" ,
	coalesce(A."AdmissionAmount",0) - coalesce(B."AdmissionRefAmount",0) "AdmissionAmount"
   from actadmissionamount A
	left join refadmissionamount B on A."AccountId"=B."AccountId"	 

)
,LabAmount as ( 
select a."AccountId",
	sum(a."Cash") "LabCash",
	sum(a."Card") "LabCard" ,
	sum(a."UPI") "LabUPI",
	sum(a."Online") "LabOnline" ,
	sum(a."Cheque") "LabCheque",
	sum(a."Paytm") "LabPaytm" ,
	sum(a."NotPaidTotal") "LabNotPaidTotal",
	sum(a."OtherTotal") "LabOtherTotal",
	sum(a."CardSwipeTotal") "LabCardSwipeTotal",
	sum(a."CardStandAloneTotal") "LabCardStandAloneTotal",
	sum(a."CardUPITotal") "LabCardUPITotal",
	sum(a."CardGpayTotal") "LabCardGpayTotal",
	sum(a."CashDrawerTotal") "LabCashDrawerTotal",
	sum(a."CashChequeTotal") "LabCashChequeTotal",
	sum(a."CashDDTotal") "LabCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "LabWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "LabWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "LabCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "LabWalletPaytmDQRTotal",
	sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")

	"LabAmount"
	from(
select 	a."AccountId",							  
	case when ar."PayTypeId"=1 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."OverallNetAmount",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."OverallNetAmount",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."OverallNetAmount",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."OverallNetAmount",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."OverallNetAmount",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."OverallNetAmount",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."OverallNetAmount",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."OverallNetAmount",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."OverallNetAmount",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."OverallNetAmount",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."OverallNetAmount",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."OverallNetAmount",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."OverallNetAmount",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."OverallNetAmount",0) else 0 end   "WalletPaytmDQRTotal"
from "Account" a		
join "NewLabBookingHeader" ar on ar."CreatedBy" = a."AccountId" and ar."Active" <> false
where case when accountid is null then 1=1 else a."AccountId"=accountid end 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ar."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end)a
group by a."AccountId" )

,PharmaSaleAmount as (
	
select a."AccountId", sum(a."Cash") "PharmaSaleCash",
	sum(a."Card") "PharmaSaleCard" ,
	sum(a."UPI") "PharmaSaleUPI",
	sum(a."Online") "PharmaSaleOnline" ,
	sum(a."Cheque") "PharmaSaleCheque",
	sum(a."Paytm") "PharmaSalePaytm" ,
	sum(a."NotPaidTotal") "PharmaSaleNotPaidTotal",
	sum(a."OtherTotal") "PharmaSaleOtherTotal",
	sum(a."CardSwipeTotal") "PharmaSaleCardSwipeTotal",
	sum(a."CardStandAloneTotal") "PharmaSaleCardStandAloneTotal",
	sum(a."CardUPITotal") "PharmaSaleCardUPITotal",
	sum(a."CardGpayTotal") "PharmaSaleCardGpayTotal",
	sum(a."CashDrawerTotal") "PharmaSaleCashDrawerTotal",
	sum(a."CashChequeTotal") "PharmaSaleCashChequeTotal",
	sum(a."CashDDTotal") "PharmaSaleCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "PharmaSaleWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "PharmaSaleWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "PharmaSaleCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "PharmaSaleWalletPaytmDQRTotal",
	 sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")

	"PharmaSaleAmount" 
	from (
select a."AccountId", 
	 case when ar."PayTypeId"=1 then  coalesce(ar."Cost",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."Cost",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."Cost",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."Cost",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."Cost",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."Cost",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."Cost",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."Cost",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."Cost",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."Cost",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."Cost",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."Cost",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."Cost",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."Cost",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."Cost",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."Cost",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."Cost",0) else 0 end   "WalletPaytmDQRTotal"
from "Account" a
join "Receipt" ar on ar."CreatedBy" = a."AccountId" and ar."ReceiptAreaTypeId"=1
join "PharmacySaleHeader" ps on ps."PharmacySaleHeaderId"=ar."RespectiveId"
where case when accountid is null then 1=1 else a."AccountId"=accountid end
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ps."LocationId"=locationId END 
		and case when "fromDate" is null then 1=1 
else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end	
	)a
group by a."AccountId"
)
,PharmaReturnAmount as (
select a."AccountId", 
	sum(a."Cash") "PharmaReturnCash",
	sum(a."Card") "PharmaReturnCard" ,
	sum(a."UPI") "PharmaReturnUPI",
	sum(a."Online") "PharmaReturnOnline" ,
	sum(a."Cheque") "PharmaReturnCheque",
	sum(a."Paytm") "PharmaReturnPaytm" ,
	sum(a."NotPaidTotal") "PharmaReturnNotPaidTotal",
	sum(a."OtherTotal") "PharmaReturnOtherTotal",
	sum(a."CardSwipeTotal") "PharmaReturnCardSwipeTotal",
	sum(a."CardStandAloneTotal") "PharmaReturnCardStandAloneTotal",
	sum(a."CardUPITotal") "PharmaReturnCardUPITotal",
	sum(a."CardGpayTotal") "PharmaReturnCardGpayTotal",
	sum(a."CashDrawerTotal") "PharmaReturnCashDrawerTotal",
	sum(a."CashChequeTotal") "PharmaReturnCashChequeTotal",
	sum(a."CashDDTotal") "PharmaReturnCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "PharmaReturnWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "PharmaReturnWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "PharmaReturnCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "PharmaReturnWalletPaytmDQRTotal",
	 sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")
 
	"PharmaReturnAmount"
	from(
select a."AccountId", 
	 case when ar."PayTypeId"=1 then  coalesce(ar."Cost",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."Cost",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."Cost",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."Cost",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."Cost",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."Cost",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."Cost",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."Cost",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."Cost",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."Cost",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."Cost",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."Cost",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."Cost",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."Cost",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."Cost",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."Cost",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."Cost",0) else 0 end   "WalletPaytmDQRTotal"
		
							   
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"
left join "Receipt" ar on ar."CreatedBy" = a."AccountId" and ar."ReceiptAreaTypeId"=7
left join "SaleReturnHeader" sh on sh."SaleReturnHeaderId" = ar."RespectiveId"
where case when accountid is null then 1=1 else ar."CreatedBy"=accountid end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE LAM."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end	
	)a
group by a."AccountId"
)

 ,PharmaAmount as (
 select a."AccountId", 	
 	 coalesce(a."PharmaSaleCash",0) - coalesce(b."PharmaReturnCash",0) as  "PharmaSaleCash" ,
	 coalesce(a."PharmaSaleCard",0) - coalesce(b."PharmaReturnCard",0) as  "PharmaSaleCard" ,
	 coalesce(a."PharmaSaleUPI",0) - coalesce(b."PharmaReturnUPI",0) as  "PharmaSaleUPI" ,
	 coalesce(a."PharmaSaleOnline",0) - coalesce(b."PharmaReturnOnline",0) as  "PharmaSaleOnline" ,
	 coalesce(a."PharmaSaleCheque",0) - coalesce(b."PharmaReturnCheque",0) as  "PharmaSaleCheque" ,
	 coalesce(a."PharmaSalePaytm",0) - coalesce(b."PharmaReturnPaytm",0) as  "PharmaSalePaytm" ,
	 coalesce(a."PharmaSaleNotPaidTotal",0) - coalesce(b."PharmaReturnNotPaidTotal",0) as  "PharmaSaleNotPaidTotal" ,
	 coalesce(a."PharmaSaleOtherTotal",0) - coalesce(b."PharmaReturnOtherTotal",0) as  "PharmaSaleOtherTotal" ,
	 coalesce(a."PharmaSaleCardSwipeTotal",0) - coalesce(b."PharmaReturnCardSwipeTotal",0) as  "PharmaSaleCardSwipeTotal" ,
	 coalesce(a."PharmaSaleCardStandAloneTotal",0) - coalesce(b."PharmaReturnCardStandAloneTotal",0) as  "PharmaSaleCardStandAloneTotal" ,
	 coalesce(a."PharmaSaleCardUPITotal",0) - coalesce(b."PharmaReturnCardUPITotal",0) as  "PharmaSaleCardUPITotal" ,
	 coalesce(a."PharmaSaleCardGpayTotal",0) - coalesce(b."PharmaReturnCardGpayTotal",0) as  "PharmaSaleCardGpayTotal" ,
	 coalesce(a."PharmaSaleCashDrawerTotal",0) - coalesce(b."PharmaReturnCashDrawerTotal",0) as  "PharmaSaleCashDrawerTotal" ,
	 coalesce(a."PharmaSaleCashDDTotal",0) - coalesce(b."PharmaReturnCashDDTotal",0) as  "PharmaSaleCashDDTotal" ,
	 coalesce(a."PharmaSaleCashChequeTotal",0) - coalesce(b."PharmaReturnCashChequeTotal",0) as  "PharmaSaleCashChequeTotal" ,
	 coalesce(a."PharmaSaleWalletPaytmOfflineTotal",0) - coalesce(b."PharmaReturnWalletPaytmOfflineTotal",0) as  "PharmaSaleWalletPaytmOfflineTotal" ,
	 coalesce(a."PharmaSaleWalletPhonePeOfflineTotal",0) - coalesce(b."PharmaReturnWalletPhonePeOfflineTotal",0) as  "PharmaSaleWalletPhonePeOfflineTotal" ,
	 coalesce(a."PharmaSaleCashRemoteDepositTotal",0) - coalesce(b."PharmaReturnCashRemoteDepositTotal",0) as  "PharmaSaleCashRemoteDepositTotal" ,
	 coalesce(a."PharmaSaleWalletPaytmDQRTotal",0) - coalesce(b."PharmaReturnWalletPaytmDQRTotal",0) as  "PharmaSaleWalletPaytmDQRTotal" ,
	coalesce(a."PharmaSaleAmount",0) - coalesce(b."PharmaReturnAmount",0) as  "PharmaAmount" 
 from PharmaSaleAmount a
 	left join PharmaReturnAmount b on a."AccountId"=b."AccountId"
 )
 
select distinct  a."AccountId",a."EmployeeName",a."RoleName",
                     pr."RegistrationCashTotal",pr."RegistrationCardTotal",pr."RegistrationUPITotal",pr."RegistrationOnlineTotal",pr."RegistrationChequeTotal",pr."RegistrationPaytmTotal",
						 pr.  "RegistrationNotPaidTotal" ,pr. "RegistrationOtherTotal" ,pr. "RegistrationCardSwipeTotal" ,pr."RegistrationCardStandAloneTotal" ,
				    pr. "RegistrationCardUPITotal" ,pr."RegistrationCardGpayTotal" ,pr."RegistrationCashDrawerTotal" ,pr."RegistrationCashChequeTotal" ,
				    pr. "RegistrationCashDDTotal" ,pr."RegistrationWalletPaytmOfflineTotal" ,pr."RegistrationWalletPhonePeOfflineTotal" ,pr."RegistrationCashRemoteDepositTotal" ,
				      pr. "RegistrationWalletPaytmDQRTotal" ,
						pr."registrationamount",
						  ap."AppointmentCashTotal",ap."AppointmentCardTotal",ap."AppointmentUPITotal",ap."AppointmentOnlineTotal",ap."AppointmentChequeTotal",ap."AppointmentPaytmTotal",
						 ap."AppointmentNotPaidTotal" ,ap."AppointmentOtherTotal" ,ap."AppointmentCardSwipeTotal" ,ap."AppointmentCardStandAloneTotal" ,
				   ap."AppointmentCardUPITotal" ,ap."AppointmentCardGpayTotal" ,ap."AppointmentCashDrawerTotal" ,ap."AppointmentCashChequeTotal" ,
				    ap."AppointmentCashDDTotal" ,ap."AppointmentWalletPaytmOfflineTotal" ,ap."AppointmentWalletPhonePeOfflineTotal" ,ap."AppointmentCashRemoteDepositTotal" ,
				     ap."AppointmentWalletPaytmDQRTotal" ,
						ap."AppointmentAmount",
						  ad."AdmissionCashTotal",ad."AdmissionCardTotal",ad."AdmissionUPITotal",ad."AdmissionOnlineTotal",ad."AdmissionChequeTotal",ad."AdmissionPaytmTotal",
						 ad."AdmissionCardUPITotal" ,ad."AdmissionCardGpayTotal" ,ad."AdmissionCashDrawerTotal" ,ad."AdmissionCashChequeTotal" ,
						 ad."AdmissionNotPaidTotal" ,ad."AdmissionOtherTotal" ,ad."AdmissionCardSwipeTotal" ,ad."AdmissionCardStandAloneTotal" ,
				    ad."AdmissionCashDDTotal" ,ad."AdmissionWalletPaytmOfflineTotal" ,ad."AdmissionWalletPhonePeOfflineTotal" ,ad."AdmissionCashRemoteDepositTotal" ,
				     ad."AdmissionWalletPaytmDQRTotal" , 
						ad."AdmissionAmount",
						  lb."LabCash", lb."LabCard",lb."LabUPI", lb."LabOnline",lb."LabCheque", lb."LabPaytm",
						    lb."LabNotPaidTotal" , lb."LabOtherTotal" , lb."LabCardSwipeTotal" , lb."LabCardStandAloneTotal" ,
						 lb."LabCardUPITotal" ,lb."LabCardGpayTotal" ,lb."LabCashDrawerTotal" ,lb."LabCashChequeTotal" ,
				   lb."LabCashDDTotal" ,lb."LabWalletPaytmOfflineTotal" ,lb."LabWalletPhonePeOfflineTotal" ,lb."LabCashRemoteDepositTotal" ,
				     lb."LabWalletPaytmDQRTotal" 
						,lb."LabAmount",
sum(pa."PharmaSaleCash") over(partition by a."AccountId")  "PharmacySaleCash",
sum(pa."PharmaSaleCard") over(partition by a."AccountId") 	"PharmacySaleCard",
sum(pa."PharmaSaleUPI") over(partition by a."AccountId")  "PharmacySaleUPI",
sum(pa."PharmaSaleOnline") over(partition by a."AccountId") 	"PharmacySaleOnline",
sum(pa."PharmaSaleCheque") over(partition by a."AccountId")  "PharmacySaleCheque",
sum(pa."PharmaSalePaytm") over(partition by a."AccountId") 	"PharmacySalePaytm",

sum(pa."PharmaSaleNotPaidTotal") over(partition by a."AccountId") 	"PharmacySaleNotPaidTotal",
sum(pa."PharmaSaleOtherTotal") over(partition by a."AccountId") 	"PharmacySaleOtherTotal",
sum(pa."PharmaSaleCardSwipeTotal") over(partition by a."AccountId") 	"PharmacySaleCardSwipeTotal",
sum(pa."PharmaSaleCardStandAloneTotal") over(partition by a."AccountId") 	"PharmacySaleCardStandAloneTotal",
sum(pa."PharmaSaleCardUPITotal") over(partition by a."AccountId") 	"PharmacySaleCardUPITotal",
sum(pa."PharmaSaleCardGpayTotal") over(partition by a."AccountId") 	"PharmacySaleCardGpayTotal",
sum(pa."PharmaSaleCashDrawerTotal") over(partition by  a."AccountId") 	"PharmacySaleCashDrawerTotal",
sum(pa."PharmaSaleCashChequeTotal") over(partition by a."AccountId") 	"PharmacySaleCashChequeTotal",
sum(pa."PharmaSaleCashDDTotal") over(partition by a."AccountId") 	"PharmacySaleCashDDTotal",
sum(pa."PharmaSaleWalletPaytmOfflineTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPaytmOfflineTotal",
sum(pa."PharmaSaleWalletPhonePeOfflineTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPhonePeOfflineTotal",
sum(pa."PharmaSaleCashRemoteDepositTotal") over(partition by a."AccountId") 	"PharmacySaleCashRemoteDepositTotal",
sum(pa."PharmaSaleWalletPaytmDQRTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPaytmDQRTotal",
sum(pa."PharmaAmount") over(partition by a."AccountId") "PharmacyAmount",
coalesce(pr."RegistrationCashTotal",0)+coalesce(ap."AppointmentCashTotal",0)+coalesce(ad."AdmissionCashTotal",0)+coalesce(lb."LabCash",0)+coalesce(sum(pa."PharmaSaleCash") over(partition by a."AccountId") ,0) "TotalCash",
coalesce(pr."RegistrationCardTotal",0)+	coalesce(ap."AppointmentCardTotal",0)+coalesce(ad."AdmissionCardTotal",0)+coalesce(lb."LabCard",0)+coalesce(sum(pa."PharmaSaleCard") over(partition by a."AccountId"),0)  "TotalCard",	
coalesce(pr."RegistrationUPITotal",0)+	coalesce(ap."AppointmentUPITotal",0)+coalesce(ad."AdmissionUPITotal",0)+coalesce(lb."LabUPI",0)+coalesce(sum(pa."PharmaSaleUPI") over(partition by a."AccountId") ,0) "TotalUPI",
coalesce(pr."RegistrationOnlineTotal",0)+coalesce(ap."AppointmentOnlineTotal",0)+coalesce(ad."AdmissionOnlineTotal",0)+coalesce(lb."LabOnline",0)+coalesce(sum(pa."PharmaSaleOnline") over(partition by a."AccountId"),0)  "TotalOnline",	
coalesce(pr."RegistrationChequeTotal",0)+coalesce(ap."AppointmentChequeTotal",0)+	coalesce(ad."AdmissionChequeTotal",0)+coalesce(lb."LabCheque",0)+coalesce(sum(pa."PharmaSaleCheque") over(partition by a."AccountId") ,0) "TotalCheque",
coalesce(pr."RegistrationPaytmTotal",0)+coalesce(ap."AppointmentPaytmTotal",0)+	coalesce(ad."AdmissionPaytmTotal",0)+coalesce(lb."LabPaytm",0)+coalesce(sum(pa."PharmaSalePaytm") over(partition by a."AccountId"),0)  "TotalPaytm",	
coalesce(pr."RegistrationNotPaidTotal",0)+coalesce(ap."AppointmentPaytmTotal",0)+coalesce(ad."AdmissionNotPaidTotal",0)+coalesce(lb."LabNotPaidTotal",0)+coalesce(sum(pa."PharmaSaleNotPaidTotal") over(partition by a."AccountId"),0)  "TotalNotPaid",
coalesce(pr."RegistrationOtherTotal",0)+coalesce(ap."AppointmentOtherTotal",0)+	coalesce(ad."AdmissionOtherTotal",0)+coalesce(lb."LabOtherTotal",0)+coalesce(sum(pa."PharmaSaleOtherTotal") over(partition by a."AccountId"),0)  "TotalOther",
coalesce(pr."RegistrationCardSwipeTotal",0)+coalesce(ap."AppointmentCardSwipeTotal",0)+	coalesce(ad."AdmissionCardSwipeTotal",0)+coalesce(lb."LabCardSwipeTotal",0)+coalesce(sum(pa."PharmaSaleCardSwipeTotal") over(partition by a."AccountId"),0)  "CardSwipeTotal",
coalesce(pr."RegistrationCardStandAloneTotal",0)+coalesce(ap."AppointmentCardStandAloneTotal",0)+coalesce(ad."AdmissionCardStandAloneTotal",0)+coalesce(lb."LabCardStandAloneTotal",0)+coalesce(sum(pa."PharmaSaleCardStandAloneTotal") over(partition by a."AccountId"),0)  "CardStandAloneTotal",
coalesce(pr."RegistrationCardUPITotal",0)+coalesce(ap."AppointmentCardUPITotal",0)+coalesce(ad."AdmissionCardUPITotal",0)+coalesce(lb."LabCardUPITotal",0)+coalesce(sum(pa."PharmaSaleCardUPITotal") over(partition by a."AccountId"),0)  "CardUPITotal",
coalesce(pr."RegistrationCardGpayTotal",0)+coalesce(ap."AppointmentCardGpayTotal",0)+coalesce(ad."AdmissionCardGpayTotal",0)+coalesce(lb."LabCardGpayTotal",0)+coalesce(sum(pa."PharmaSaleCardGpayTotal") over(partition by a."AccountId"),0)  "CardGpayTotal",
coalesce(pr."RegistrationCashDrawerTotal",0)+coalesce(ap."AppointmentCashDrawerTotal",0)+coalesce(ad."AdmissionCashDrawerTotal",0)+coalesce(lb."LabCashDrawerTotal",0)+coalesce(sum(pa."PharmaSaleCashDrawerTotal") over(partition by a."AccountId"),0)  "CashDrawerTotal",
coalesce(pr."RegistrationCashChequeTotal",0)+coalesce(ap."AppointmentCashChequeTotal",0)+coalesce(ad."AdmissionCashChequeTotal",0)+coalesce(lb."LabCashChequeTotal",0)+coalesce(sum(pa."PharmaSaleCashChequeTotal") over(partition by a."AccountId"),0) "CashChequeTotal",
coalesce(pr."RegistrationCashDDTotal",0)+coalesce(ap."AppointmentCashDDTotal",0)+coalesce(ad."AdmissionCashDDTotal",0)+coalesce(lb."LabCashDDTotal",0)+coalesce(sum(pa."PharmaSaleCashDDTotal") over(partition by a."AccountId"),0)  "CashDDTotal",
coalesce(pr."RegistrationWalletPaytmOfflineTotal",0)+coalesce(ap."AppointmentWalletPaytmOfflineTotal",0)+coalesce(ad."AdmissionWalletPaytmOfflineTotal",0)+coalesce(lb."LabWalletPaytmOfflineTotal",0)+coalesce(sum(pa."PharmaSaleWalletPaytmOfflineTotal")over(partition by a."AccountId"),0)  "WalletPaytmOfflineTotal",
coalesce(ap."AppointmentWalletPhonePeOfflineTotal",0)+coalesce(ap."AppointmentWalletPhonePeOfflineTotal",0)+coalesce(ad."AdmissionWalletPhonePeOfflineTotal",0)+coalesce(lb."LabWalletPhonePeOfflineTotal",0)+coalesce(sum(pa."PharmaSaleWalletPhonePeOfflineTotal") over(partition by a."AccountId"),0)  "WalletPhonePeOfflineTotal",
coalesce(pr."RegistrationCashRemoteDepositTotal",0)+coalesce(ap."AppointmentCashRemoteDepositTotal",0)+	coalesce(ad."AdmissionCashRemoteDepositTotal",0)+coalesce(lb."LabCashRemoteDepositTotal",0)+coalesce(sum(pa."PharmaSaleCashRemoteDepositTotal")over(partition by a."AccountId"),0)  "CashRemoteDepositTotal",
coalesce(pr."RegistrationWalletPaytmDQRTotal",0)+coalesce(ap."AppointmentWalletPaytmDQRTotal",0)+coalesce(ad."AdmissionWalletPaytmDQRTotal",0)+coalesce(lb."LabWalletPaytmDQRTotal",0)+coalesce(sum(pa."PharmaSaleWalletPaytmDQRTotal") over(partition by a."AccountId"),0)  "WalletPaytmDQRTotal",

coalesce(pr."registrationamount",0)+coalesce(ap."AppointmentAmount",0)+coalesce(ad."AdmissionAmount",0)+coalesce(lb."LabAmount",0)
+coalesce(sum(pa."PharmaAmount") over(partition by a."AccountId"),0) "Total"

from accountdata a

left join patientRegistrationamount pr on pr."AccountId"=a."AccountId"
left join appointmentamount ap on ap."AccountId"=a."AccountId"
left join admissionamount ad on ad."AccountId"=a."AccountId"
left join LabAmount lb on lb."AccountId"=a."AccountId"
left join PharmaAmount pa on pa."AccountId"=a."AccountId"
;
	end
$BODY$;

-----------------------------------------------------------------------Chandana 15Sep2023------------------------------------------------------------

 DROP FUNCTION IF EXISTS public."udf_report_BillDiscount"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_report_BillDiscount"(
	"fromDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	locationid integer DEFAULT NULL::integer,
	moduleid integer DEFAULT NULL::integer)
    RETURNS TABLE("TotalItems" bigint, "PatientName" text, "Cost" numeric, "UMRNo" character varying, "ReceiptAreaTypeId" integer, "Type" character varying, "Discount" numeric, "Total" numeric, "CreatedBy" integer, "createdDate" timestamp without time zone, "BilledBy" text, "LocationId" integer, "LocationName" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

 with discountData as(
	 --patient 
        SELECT A."LocationId",A."FullName",A."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."Amount",A."DiscountInRupees" "Discount",A."Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "Patient" A
         join "Receipt" r on r."RespectiveId"=A."PatientId" and r."ReceiptAreaTypeId" =3
	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where A."DiscountInRupees" >= 0
	 			 and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 				and case when "toDate" is null then 1=1 else  A."CreatedDate"<=  "toDate" end 
	 UNION ALL
	--appointment
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."Amount",A."Discount",A."Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "Appointment" A
	  join "Patient" p on p."PatientId" = A."PatientId"	 
	join "Receipt" r on r."RespectiveId"=A."AppointmentId" and r."ReceiptAreaTypeId" =4
	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where A."PaymentStatus"<>False and A."Active"<>false and  A."Status" <> 'C' and A."Discount" >= 0
	 			 and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 				and case when "toDate" is null then 1=1 else  A."CreatedDate"<=  "toDate" end 
  
UNION ALL
	--scan
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."ActualAmount" "Amount",A."DiscountAmount" "Discount",A."Amount" "Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "BookScanAppointment" A
	 join "Patient" p on p."PatientId" = A."PatientId"
	 join "Receipt" r on r."RespectiveId"=A."BookScanAppointmentId" and r."ReceiptAreaTypeId" =10
	 	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where  A."Status" <> 'C' and A."DiscountAmount" >= 0
	 		and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  A."CreatedDate"<=  "toDate" end 
UNION ALL
	--lab
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."OverallTotalAmount" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "NewLabBookingHeader" A
          join "Patient" p on p."PatientId" = A."PatientId"
	 join "Receipt" r on r."RespectiveId"=A."NewLabBookingHeaderId" and r."ReceiptAreaTypeId" =8
	 	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where  A."Active" <> false and A."OverallDiscount" >= 0 
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  A."CreatedDate" <=  "toDate" end 
UNION ALL
--pharma	
        SELECT A."LocationId",p."FullName",p."UMRNo",r."ReceiptAreaTypeId",rt."Name" "Type",A."Total" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",A."CreatedBy",A."CreatedDate",ac."FullName" as "BilledBy"
          from "PharmacySaleHeader" A
           join "Patient" p on p."PatientId" = A."PatientId"
	  join "Receipt" r on r."RespectiveId"=A."PharmacySaleHeaderId" and r."ReceiptAreaTypeId" =1
	 join "Account" ac on ac."AccountId"=A."CreatedBy"
	 join "ReceiptAreaType" rt on rt."ReceiptAreaTypeId"=r."ReceiptAreaTypeId"
         where A."OverallDiscount" >= 0 
	 		and case when "fromDate" is null then 1=1 else "fromDate"<=  A."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  A."CreatedDate" <=  "toDate" end 
 )
 select count(*) over() as  "TotalItems",d."FullName" , d."Amount",d."UMRNo",d."ReceiptAreaTypeId",d."Type",d."Discount",d."Total",d."CreatedBy",d."CreatedDate",d."BilledBy",d."LocationId",l."Name" as "LocationName"  from discountData d
   join "Location" l on l."LocationId" =d."LocationId"
   where 
   	case when "moduleid" is null then 1=1 else d."ReceiptAreaTypeId" = "moduleid" end
and 	case when "locationid" is null then 1=1 else d."LocationId" = locationid end
	and case when "fromDate" is null then 1=1 else "fromDate"<=  d."CreatedDate" end 
 	and case when "toDate" is null then 1=1 else  d."CreatedDate" <=  "toDate" end 
order by d."CreatedDate" desc
;
	
end
$BODY$;

--------------------------------------------------------------------------Kalyan 15Sep2023---------------------------------------------------------------------------

Alter Table If Exists "ModulesMaster"
Add Column If Not Exists "IsPackageApplicable" boolean DEFAULT false;

INSERT INTO "ModulesMaster"("ModuleName","ModuleIcon","ModuleDescription","CreatedBy","CreatedDate","IsPackageApplicable")
SELECT 'Pharmacy Medications','mdi mdi-pill','This is for package',6776,now(),true
WHERE
NOT EXISTS (
SELECT "ModuleName" FROM "ModulesMaster" WHERE "ModuleName" = 'Pharmacy Medications'
);

------------------------------------------------------------------------
Alter Table If Exists "PharmacyProduct"
Add Column If Not Exists "ModulesMasterId" integer,
drop constraint if exists "FK_PharmacyProduct_ModulesMasterId",
ADD CONSTRAINT "FK_PharmacyProduct_ModulesMasterId" FOREIGN KEY ("ModulesMasterId") REFERENCES public."ModulesMaster"("ModulesMasterId");

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'PharmacyProduct'
            )
        THEN
            UPDATE "PharmacyProduct"
            SET "ModulesMasterId" = (select "ModulesMasterId" from "ModulesMaster" where "ModuleName" = 'Pharmacy Medications');
        END IF ;
    END
   $$ ;

---------------------------------------------------------------

 DROP FUNCTION IF EXISTS public."udf_fetch_moduleChargeDetails"(integer, integer);

CREATE OR REPLACE FUNCTION public."udf_fetch_moduleChargeDetails"(
	"@modulesMasterId" integer DEFAULT NULL::integer,
	"@locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("LocationId" integer, "ModulesMasterId" integer, "ModuleName" character varying, "ModuleIcon" character varying, "ReferenceId" integer, "ChargeName" text, "DepartmentId" integer, "DepartmentName" text, "ChargeGroupId" integer, "ChargeGroupName" text, "RepeatTypeId" integer, "RepeatTypeName" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN
	RETURN query SELECT distinct
-- 		CMD."ChargeModuleDetailsId",
-- 		CMD."ChargeModuleCategoryId",
		CMD."LocationId",
		CMC."ModulesMasterId",
		MM."ModuleName",
		MM."ModuleIcon",
-- 		CMD."Amount",
		CMD."ReferenceId",
		LMD."TestName" AS "ChargeName",
		NULL :: INT AS "DepartmentId",
		NULL :: TEXT AS "DepartmentName",
		NULL :: INT AS "ChargeGroupId",
		NULL :: TEXT AS "ChargeGroupName",
		NULL :: INT "RepeatTypeId",
		NULL :: TEXT "RepeatTypeName"
	FROM
		"ChargeModuleDetails" CMD
	JOIN "ChargeModuleCategory" CMC ON CMC."ChargeModuleCategoryId" = CMD."ChargeModuleCategoryId"
	JOIN "ModulesMaster" MM ON MM."ModulesMasterId" = CMC."ModulesMasterId"
	JOIN "LabMainDetail" LMD ON LMD."LabMainDetailId" = CMD."ReferenceId"
	AND MM."ModuleName" = 'Lab'
	WHERE
		MM."ModulesMasterId" = "@modulesMasterId"
	AND CMD."LocationId" = "@locationId"
	UNION ALL
		SELECT DIstinct
-- 			CMD."ChargeModuleDetailsId",
-- 			CMD."ChargeModuleCategoryId",
			CMD."LocationId",
			CMC."ModulesMasterId",
			MM."ModuleName",
			MM."ModuleIcon",
-- 			CMD."Amount",
			CMD."ReferenceId",
			STM."ScanTestName" AS "ChargeName",
			NULL :: INT AS "DepartmentId",
			NULL :: TEXT AS "DepartmentName",
			NULL :: INT AS "ChargeGroupId",
			NULL :: TEXT AS "ChargeGroupName",
			NULL :: INT "RepeatTypeId",
			NULL :: TEXT "RepeatTypeName"
		FROM
			"ChargeModuleDetails" CMD
		JOIN "ChargeModuleCategory" CMC ON CMC."ChargeModuleCategoryId" = CMD."ChargeModuleCategoryId"
		JOIN "ModulesMaster" MM ON MM."ModulesMasterId" = CMC."ModulesMasterId"
		JOIN "ScanTestMaster" STM ON STM."ScanTestMasterId" = CMD."ReferenceId"
		AND MM."ModuleName" = 'Scan'
		WHERE
			MM."ModulesMasterId" = "@modulesMasterId"
		AND CMD."LocationId" = "@locationId"
		UNION ALL
			SELECT distinct
-- 				CMD."ChargeModuleDetailsId",
-- 				CMD."ChargeModuleCategoryId",
				CMD."LocationId",
				CMC."ModulesMasterId",
				MM."ModuleName",
				MM."ModuleIcon",
-- 				CMD."Amount",
				CMD."ReferenceId",
				s."Name" AS "ChargeName",
				NULL :: INT AS "DepartmentId",
				NULL :: TEXT AS "DepartmentName",
				NULL :: INT AS "ChargeGroupId",
				NULL :: TEXT AS "ChargeGroupName",
				NULL :: INT "RepeatTypeId",
				NULL :: TEXT "RepeatTypeName"
			FROM
				"ChargeModuleDetails" CMD
			JOIN "ChargeModuleCategory" CMC ON CMC."ChargeModuleCategoryId" = CMD."ChargeModuleCategoryId"
			JOIN "ModulesMaster" MM ON MM."ModulesMasterId" = CMC."ModulesMasterId"
			JOIN "Surgery" s ON s."SurgeryId" = CMD."ReferenceId"
			AND MM."ModuleName" = 'OT'
			WHERE
				MM."ModulesMasterId" = "@modulesMasterId"
			AND CMD."LocationId" = "@locationId"
			UNION ALL
			SELECT distinct
-- 		CMD."ChargeModuleDetailsId",
-- 		CMD."ChargeModuleCategoryId",
		NULL :: INT AS "LocationId",
		s."ModulesMasterId",
		MM."ModuleName",
		MM."ModuleIcon",
-- 		CMD."Amount",
		s."PharmacyProductId",
		s."ProductName" AS "ChargeName" ,
		NULL :: INT AS "DepartmentId",
		NULL :: TEXT AS "DepartmentName",
		NULL :: INT AS "ChargeGroupId",
		NULL :: TEXT AS "ChargeGroupName",
		NULL :: INT "RepeatTypeId",
		NULL :: TEXT "RepeatTypeName"
	FROM
		"PharmacyProduct" s
	    JOIN "ModulesMaster" MM ON MM."ModulesMasterId" = s."ModulesMasterId"
	      AND MM."ModuleName" = 'Pharmacy Medications'
			WHERE
				MM."ModulesMasterId" = "@modulesMasterId" and MM."ModuleName" = 'Pharmacy Medications'
			
			UNION ALL
				SELECT DISTINCT
-- 					CMD."ChargeModuleDetailsId",
-- 					CMD."ChargeModuleCategoryId",
					CMD."LocationId",
					CMC."ModulesMasterId",
					MM."ModuleName",
					MM."ModuleIcon",
-- 					CMD."Amount",
					CMD."ReferenceId",
					c."ChargeName",
					d."DepartmentId" AS "DepartmentId",
					d."DepartmentName" AS "DepartmentName",
					g."ChargeGroupId",
					g."ChargeGroupName",
					c."RepeatTypeId",
					t."RepeatTypeName" "Unit"
				FROM
					"ChargeModuleDetails" CMD
				JOIN "ChargeModuleCategory" CMC ON CMC."ChargeModuleCategoryId" = CMD."ChargeModuleCategoryId"
				JOIN "ModulesMaster" MM ON MM."ModulesMasterId" = CMC."ModulesMasterId"
				JOIN "Charge" C ON C."ModulesMasterId" = CMC."ModulesMasterId"
				AND C."ChargeId" = CMD."ReferenceId"
				LEFT JOIN "ChargeGroup" G ON G."ChargeGroupId" = C."ChargeGroupId"
				LEFT JOIN "Department" d ON G."DepartmentId" = d."DepartmentId"
				LEFT JOIN "RepeatType" t ON t."RepeatTypeId" = c."RepeatTypeId"
				WHERE
					1 = 1
				AND MM."ModulesMasterId" = "@modulesMasterId"
				AND MM."ModuleName" = 'Services'
				AND CMD."LocationId" = "@locationId" ;
				END 
$BODY$;


--------------------------------------------------------------------Subramanyam 19Sep2023------------------------------------------------------

INSERT INTO "LogType"("LogTypeId","LogTypeName","Active")
SELECT 99,'Payment',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM "LogType" WHERE "LogTypeName" = 'Payment'
);
--------------------------------------------------------------------Radhika 19Sep2023------------------------------------------------------

Alter Table If Exists "CommonEncounter"
Add Column If Not Exists "GPLA" text;
-------------------------------------------------------------------Mounika A20Sep2023---------------------------------------------------
DROP FUNCTION IF EXISTS "UDF_Expiry"( int,int,int,date,date);
CREATE OR REPLACE FUNCTION "UDF_Expiry"(locationId int,pharmacyWareHouseId int,retailPharmacyId int,fromDate date,toDate date)
    RETURNS TABLE("BatchNumber" character varying, "ExpiryDate" date, "QuantityIn" integer, "PurchaseRate" numeric,"Mrp" numeric,"ProductName"  character varying,"LossAmount" numeric)
	LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
 if pharmacyWareHouseId is null then
	 
	return query   select RS."BatchNumber",RS."ExpiryDate"::date,RS."QuantityIn",RS."PurchaseRate",RS."Mrp"
	,PP."ProductName",(RS."PurchaseRate"*RS."QuantityIn") as "LossAmount"
 from "PharmacyStock" RS
left join "PharmacyProduct" PP on PP."PharmacyProductId"=RS."PharmacyProductId"
left join "PharmacyWareHouse" PW on PW."PharmacyWareHouseId"=RS."PharmacyWareHouseId"
where   PW."LocationId" = locationId 
 
and  RS."ExpiryDate"::DATE >= fromDate::DATE 
and  RS."ExpiryDate"::date  <= toDate::DATE ;
    end if;

 if retailPharmacyId is null then
	 
	return query   select RS."BatchNumber",RS."ExpiryDate"::date,RS."QuantityIn",RS."PurchaseRate",RS."Mrp"
	,PP."ProductName",(RS."PurchaseRate"*RS."QuantityIn") as "LossAmount"
 from "PharmacyStock" RS
left join "PharmacyProduct" PP on PP."PharmacyProductId"=RS."PharmacyProductId"
left join "PharmacyWareHouse" PW on PW."PharmacyWareHouseId"=RS."PharmacyWareHouseId"
where   PW."LocationId" = locationId 
and PW."PharmacyWareHouseId"=pharmacyWareHouseId 
and  RS."ExpiryDate"::DATE >= fromDate::DATE 
and  RS."ExpiryDate"::date  <= toDate::DATE ;
         
else		  
  return query  select  RS."BatchNumber",RS."ExpiryDate"::date,RS."QuantityIn",RS."PurchaseRate",RS."Mrp",PP."ProductName",(RS."PurchaseRate"*RS."QuantityIn") as "LossAmount"
               		from "PharmacyRetailStock" RS
                    left join "PharmacyProduct" PP on PP."PharmacyProductId" = RS."PharmacyProductId"
                    left join "RetailWareHouseLink" PS on PS."RetailWareHouseLinkId" = RS."RetailWareHouseLinkId"
                    where  PS."RetailPharmacyId" =retailPharmacyId 
					and  PS."PharmacyWareHouseId"= pharmacyWareHouseId 
					and RS."ExpiryDate"::DATE >= fromDate::DATE 
					and  RS."ExpiryDate"::date  <= toDate::DATE;
					   end if;
end;
$BODY$;
-------------------------------------------------------------------Shiva Ram  21Sep2023------------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_uiReport_fetch_Appointments_Location1"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer);

CREATE OR REPLACE FUNCTION public."udf_uiReport_fetch_Appointments_Location1"(
	locationid integer DEFAULT NULL::integer,
	"appointmentNo" text DEFAULT NULL::text,
	"departmentId" integer[] DEFAULT NULL::integer[],
	"providerId" integer[] DEFAULT NULL::integer[],
	"patientId" integer[] DEFAULT NULL::integer[],
	"uMRNo" text DEFAULT NULL::text,
	"patientReferredById" integer[] DEFAULT NULL::integer[],
	"referredByName" text DEFAULT NULL::text,
	mobile text DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"visitTypeId" integer[] DEFAULT NULL::integer[],
	"paymentStatus" boolean DEFAULT NULL::boolean,
	status text[] DEFAULT NULL::text[],
	"pageIndex" integer DEFAULT 0,
	"pageSize" integer DEFAULT 10)
    RETURNS TABLE("DepartmentId" text, "DepartmentName" character varying, "ProviderId" text, "ProviderName" character varying, "AppointmentTypeName" character varying, "AppointmentDate" date, "AppointmentNo" character varying, "PatientId" integer, "Name" character varying, "ReferredByName" character varying, "PatientName" character varying, "PatientAge" smallint, "UMRNo" character varying, "Mobile" character varying, "PatientGender" character, "AppointmentTime" time without time zone, "VisitType" character, "PaymentType" character varying, "PaymentNumber" character varying, "TotalAppointments" bigint, "TotalAmount" bigint, "TotalAmountStr" text, "ReceiptCreatedByName" text, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "StreetAdress" character varying, "City" character varying, "State" character varying, "FatherOrHusband" text, "PaymentStatus" boolean, "EncounterType" encountertype_elements, "Status" text, "TypeOfPayment" character, "IsHealthCard" boolean) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 
--select * from "VisitType"
with cts as (select coalesce(A."DepartmentId"::text,'GrandTotal') "DepartmentId",
			 A."ProviderId"::text as "ProviderId", 
			 A."AppointmentDate",A."VisitTypeId" "AppointmentTypeId",
			ATN."VisitorName" "AppointmentTypeName",
			 A."AppointmentNo",A."PatientId" "PatientId",PRB."Name",Pa."ReferredByName",
			 Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentTime",A."VisitType",
			 case when ATN."VisitorName"='Follow Up' and sum(A."Total")=0 then 'Free Follow Up'
			 else PT."PayTypeName" end as "PaymentType" ,A."PaymentNumber",
			 A."AppointmentId",
			 case when A."Status"='B' then 'Booked' when A."Status"='R' then 'Rescheduled' when A."Status"='C' then 'Cancel' end::text as "Status",
			 COUNT(A."AppointmentNo") as "TotalAppointments" ,sum(R."Cost")::text as "TotalAmountStr" ,
			 sum(R."Cost")::bigint as "TotalAmount" ,
			 Pa."FatherOrHusband",
			 A."PaymentStatus",
			 A."EncounterType",
			 A."PaymentType" as "TypeOfPayment",R."ReceiptId",A."IsHealthCard"
			 from "Appointment" A
 			left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
			 
			 left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text			
		left join "VisitType" ATN on A."VisitTypeId"=ATN."VisitTypeId"
			 left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4
			  left join "PayType" PT on PT."PayTypeId"=R."PayTypeId"
where 
			 --A."Status"<>'C' and 
case when "departmentId" is null then 1=1 else  A."DepartmentId"  = any("departmentId") end and 
CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END and
case when "patientId" is null then 1=1 else  Pa."PatientId"  = any("patientId") end and 
case when "appointmentNo" is null then 1=1 when "appointmentNo" ='' then 1=1 else A."AppointmentNo" ilike'%'||"appointmentNo" ||'%' end  and
case when "providerId" is null then 1=1 else  A."ProviderId"  = any("providerId") end and 
case when "uMRNo" is null then 1=1 when "uMRNo" ='' then 1=1 else Pa."UMRNo" ilike'%'||"uMRNo" ||'%' end  and
case when "patientReferredById" is null then 1=1 else  Pa."PatientReferredById"  = any("patientReferredById") end and 
case when "visitTypeId" is null then 1=1 else  ATN."VisitTypeId"  = any("visitTypeId") end and 
case when "referredByName" is null then 1=1 when "referredByName" ='' then 1=1 else Pa."ReferredByName" ilike'%'||"referredByName" ||'%' end and 
case when "mobile" is null then 1=1 when "mobile" ='' then 1=1 else Pa."Mobile" ilike'%'||"mobile" ||'%' end  and
case when "payTypeId" is null then 1=1  else A."PayTypeId" ="payTypeId" end  and
case when "fromDate" is null then 1=1 else "fromDate" <=A."AppointmentDate" and A."AppointmentDate" <="toDate" end and
case when "paymentStatus" is null then 1=1  else A."PaymentStatus" ="paymentStatus" end			 
and case when "status" is null then 1=1 else  A."Status"  =any("status") end	
			 
GROUP BY GROUPING SETS((A."DepartmentId",A."ProviderId",A."PatientId",PRB."Name",
						Pa."ReferredByName",Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentDate",A."AppointmentTime",
						A."AppointmentNo",A."VisitTypeId",
						ATN."VisitorName" ,
						A."VisitType",
						PT."PayTypeName",A."PaymentNumber",
						A."AppointmentId",R."ReceiptId",
						A."Status",Pa."FatherOrHusband",A."PaymentStatus",A."EncounterType",A."PaymentType",A."IsHealthCard"), (A."DepartmentId",A."ProviderId"), ())     
order by A."AppointmentId")

select A."DepartmentId",coalesce(D."DepartmentName",'GrandTotal') "DepartmentName",
case when A."AppointmentNo" is null then 'Total'  else A."ProviderId" end "ProviderId",
case when A."AppointmentNo" is null  then 'Total'  else  Pr."FullName"  end  as "ProviderName",
 ATN."VisitorName" "AppointmentTypeName",
A."AppointmentDate",
A."AppointmentNo",A."PatientId",
case when A."AppointmentNo" is null  then null else PRB."Name"::varchar end as "Name",
case when A."AppointmentNo" is null  then null else Pa."ReferredByName"::varchar end as "ReferredByName",
case when A."AppointmentNo" is null  then null else Pa."FullName"::varchar end as "PatientName",
case when A."AppointmentNo" is null  then null else Pa."Age" end  "PatientAge",
case when A."AppointmentNo" is null  then null else Pa."UMRNo" end  "UMRNo",
case when A."AppointmentNo" is null  then null else Pa."Mobile" end  "Mobile",
case when A."AppointmentNo" is null  then null else Pa."Gender" end "PatientGender",
A."AppointmentTime",
A."VisitType",A."PaymentType",A."PaymentNumber",A."TotalAppointments",A."TotalAmount",A."TotalAmountStr",
 CA."FullName"  "ReceiptCreatedByName", R."CreatedDate" "ReceiptDate",R."ReceiptId",
 case when A."AppointmentNo" is null  then null else Pa."StreetAddress" end "StreetAddress",
case when A."AppointmentNo" is null  then null else Pa."City" end "City",
case when A."AppointmentNo" is null  then null else Pa."State" end "State",
A."FatherOrHusband",
A."PaymentStatus",A."EncounterType",A."Status",A."TypeOfPayment",A."IsHealthCard"
from cts A
left join "Department" D on A."DepartmentId"=D."DepartmentId"::text
left join "Provider" Pr on Pr."ProviderId"::text=A."ProviderId"
left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4 and R."ReceiptId"=A."ReceiptId"
Left Join "Account" CA on CA."AccountId"=R."CreatedBy"
left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text
 left join  "VisitType" ATN on ATN."VisitTypeId"=A."AppointmentTypeId"
order by A."AppointmentId"
 ;

END

$BODY$;
-------------------------------------------------------------------RajaSekhar  21Sep2023------------------------------------------------------------
alter table if exists "ObEncounter" 
add column if  not exists "NormalDeliveryForm" text;
-------------------------------------------------------------------Sravani  21Sep2023------------------------------------------------------------
DROP FUNCTION public.udf_emloyee_new_revenue(integer, integer, integer, date, date);

CREATE OR REPLACE FUNCTION "udf_Emloyee_New_Revenue"(
	accountid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer,
	roleid integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date)
    RETURNS TABLE("AccountId" integer, "EmployeeName" text, "RoleName" character varying, 
				  "RegistrationCashTotal" numeric, "RegistrationCardTotal" numeric, "RegistrationUPITotal" numeric, "RegistrationOnlineTotal" numeric, "RegistrationChequeTotal" numeric, "RegistrationPaytmTotal" numeric, "RegistrationNotPaidTotal" numeric, "RegistrationOtherTotal" numeric, "RegistrationCardSwipeTotal" numeric, "RegistrationCardStandAloneTotal" numeric, "RegistrationCardUPITotal" numeric, "RegistrationCardGpayTotal" numeric, "RegistrationCashDrawerTotal" numeric, "RegistrationCashChequeTotal" numeric, "RegistrationCashDDTotal" numeric, "RegistrationWalletPaytmOfflineTotal" numeric, "RegistrationWalletPhonePeOfflineTotal" numeric, "RegistrationCashRemoteDepositTotal" numeric, "RegistrationWalletPaytmDQRTotal" numeric, registrationamount numeric, 
				  "AppointmentCashTotal" numeric, "AppointmentCardTotal" numeric, "AppointmentUPITotal" numeric, "AppointmentOnlineTotal" numeric, "AppointmentChequeTotal" numeric, "AppointmentPaytmTotal" numeric, "AppointmentNotPaidTotal" numeric, "AppointmentOtherTotal" numeric, "AppointmentCardSwipeTotal" numeric, "AppointmentCardStandAloneTotal" numeric, "AppointmentCardUPITotal" numeric, "AppointmentCardGpayTotal" numeric, "AppointmentCashDrawerTotal" numeric, "AppointmentCashChequeTotal" numeric, "AppointmentCashDDTotal" numeric, "AppointmentWalletPaytmOfflineTotal" numeric, "AppointmentWalletPhonePeOfflineTotal" numeric, "AppointmentCashRemoteDepositTotal" numeric, "AppointmentWalletPaytmDQRTotal" numeric, "AppointmentAmount" numeric, 
				  "AdmissionCashTotal" numeric, "AdmissionCardTotal" numeric, "AdmissionUPITotal" numeric, "AdmissionOnlineTotal" numeric, "AdmissionChequeTotal" numeric, "AdmissionPaytmTotal" numeric, "AdmissionNotPaidTotal" numeric, "AdmissionOtherTotal" numeric, "AdmissionCardSwipeTotal" numeric, "AdmissionCardStandAloneTotal" numeric, "AdmissionCardUPITotal" numeric, "AdmissionCardGpayTotal" numeric, "AdmissionCashDrawerTotal" numeric, "AdmissionCashChequeTotal" numeric, "AdmissionCashDDTotal" numeric, "AdmissionWalletPaytmOfflineTotal" numeric, "AdmissionWalletPhonePeOfflineTotal" numeric, "AdmissionCashRemoteDepositTotal" numeric, "AdmissionWalletPaytmDQRTotal" numeric, "AdmissionAmount" numeric, 
				  "LabCash" numeric, "LabCard" numeric, "LabUPI" numeric, "LabOnline" numeric, "LabCheque" numeric, "LabPaytm" numeric, "LabNotPaidTotal" numeric, "LabOtherTotal" numeric, "LabCardSwipeTotal" numeric, "LabCardStandAloneTotal" numeric, "LabCardUPITotal" numeric, "LabCardGpayTotal" numeric, "LabCashDrawerTotal" numeric, "LabCashChequeTotal" numeric, "LabCashDDTotal" numeric, "LabWalletPaytmOfflineTotal" numeric, "LabWalletPhonePeOfflineTotal" numeric, "LabCashRemoteDepositTotal" numeric, "LabWalletPaytmDQRTotal" numeric, "LabAmount" numeric, 
				  "ScanCash" numeric, "ScanCard" numeric, "ScanUPI" numeric, "ScanOnline" numeric, "ScanCheque" numeric, "ScanPaytm" numeric, "ScanNotPaidTotal" numeric, "ScanOtherTotal" numeric, "ScanCardSwipeTotal" numeric, "ScanCardStandAloneTotal" numeric, "ScanCardUPITotal" numeric, "ScanCardGpayTotal" numeric, "ScanCashDrawerTotal" numeric, "ScanCashChequeTotal" numeric, "ScanCashDDTotal" numeric, "ScanWalletPaytmOfflineTotal" numeric, "ScanWalletPhonePeOfflineTotal" numeric, "ScanCashRemoteDepositTotal" numeric, "ScanWalletPaytmDQRTotal" numeric, "ScanAmount" numeric,
				  "PharmacySaleCash" numeric, "PharmacySaleCard" numeric, "PharmacySaleUPI" numeric, "PharmacySaleOnline" numeric, "PharmacySaleCheque" numeric, "PharmacySalePaytm" numeric, "PharmacySaleNotPaidTotal" numeric, "PharmacySaleOtherTotal" numeric, "PharmacySaleCardSwipeTotal" numeric, "PharmacySaleCardStandAloneTotal" numeric, "PharmacySaleCardUPITotal" numeric, "PharmacySaleCardGpayTotal" numeric, "PharmacySaleCashDrawerTotal" numeric, "PharmacySaleCashChequeTotal" numeric, "PharmacySaleCashDDTotal" numeric, "PharmacySaleWalletPaytmOfflineTotal" numeric, "PharmacySaleWalletPhonePeOfflineTotal" numeric, "PharmacySaleCashRemoteDepositTotal" numeric, "PharmacySaleWalletPaytmDQRTotal" numeric, "PharmacyAmount" numeric, 
				  "TotalCash" numeric, "TotalCard" numeric, "TotalUPI" numeric, "TotalOnline" numeric, "TotalCheque" numeric, "TotalPaytm" numeric, "NotPaidTotal" numeric, "OtherTotal" numeric, "CardSwipeTotal" numeric, "CardStandAloneTotal" numeric, "CardUPITotal" numeric, "CardGpayTotal" numeric, "CashDrawerTotal" numeric, "CashChequeTotal" numeric, "CashDDTotal" numeric, "WalletPaytmOfflineTotal" numeric, "WalletPhonePeOfflineTotal" numeric, "CashRemoteDepositTotal" numeric, "WalletPaytmDQRTotal" numeric, "Total" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
 return query 

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"  
join "Role" rol on rol."RoleId" = a."RoleId" --and lower(rol."RoleName") <> lower('Patient')
where a."RoleId"<>4
and	case when accountid is null then 1=1 else a."AccountId"=accountid end   
and	case when roleid is null then 1=1 else a."RoleId"=roleid end 	
AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE LAM."LocationId"=locationId END
)
,patientRegistrationamount as(
 select a."AccountId",
	sum(A."CashTotal") "RegistrationCashTotal"
	,sum(A."CardTotal") "RegistrationCardTotal",
 	sum(A."UPITotal") "RegistrationUPITotal",
	sum(A."OnlineTotal") "RegistrationOnlineTotal",
 	sum(A."ChequeTotal") "RegistrationChequeTotal",
	sum(A."PaytmTotal") "RegistrationPaytmTotal",
	sum(A."NotPaidTotal") "RegistrationNotPaidTotal",
	sum(A."OtherTotal") "RegistrationOtherTotal",
	sum(A."CardSwipeTotal") "RegistrationCardSwipeTotal",
	sum(A."CardStandAloneTotal") "RegistrationCardStandAloneTotal",
	sum(A."CardUPITotal") "RegistrationCardUPITotal",
	sum(A."CardGpayTotal") "RegistrationCardGpayTotal",
	sum(A."CashDrawerTotal") "RegistrationCashDrawerTotal",
	sum(A."CashChequeTotal") "RegistrationCashChequeTotal",
	sum(A."CashDDTotal") "RegistrationCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "RegistrationWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "RegistrationWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "RegistrationCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "RegistrationWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")
	+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
 	 
	registrationamount
 	from ( 
	select  a."CreatedBy"  "AccountId",   
   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
   case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal",
	case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
   case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
   case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
   case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
   case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"	
		from "Receipt" A
   join "Patient" p on  p."PatientId" =A."RespectiveId"          
   where A."ReceiptTypeId"=1 and p."Active" <> false and A."Active"<>false and A."RespectiveId" is not null
		and case when accountid is null then 1=1 else a."CreatedBy"=accountid end  
		and case when (locationId IS NULL OR locationId=0) THEN 1=1 ELSE p."LocationId"=locationId END 
		and		case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end		
	) a group by  a."AccountId"	
)

,actappointmentamount as (
	
	select a."AccountId",
	sum(A."CashTotal") "AppointmentCashTotal",
	sum(A."CardTotal") "AppointmentCardTotal",
	sum(A."UPITotal") "AppointmentUPITotal",
	sum(A."OnlineTotal") "AppointmentOnlineTotal",
	sum(A."ChequeTotal") "AppointmentChequeTotal",
	sum(A."PaytmTotal") "AppointmentPaytmTotal",
	sum(A."NotPaidTotal") "AppointmentNotPaidTotal",
	sum(A."OtherTotal") "AppointmentOtherTotal",
	sum(A."CardSwipeTotal") "AppointmentCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AppointmentCardStandAloneTotal",
	sum(A."CardUPITotal") "AppointmentCardUPITotal",
	sum(A."CardGpayTotal") "AppointmentCardGpayTotal",
	sum(A."CashDrawerTotal") "AppointmentCashDrawerTotal",
	sum(A."CashChequeTotal") "AppointmentCashChequeTotal",
	sum(A."CashDDTotal") "AppointmentCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AppointmentWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AppointmentWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AppointmentCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AppointmentWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")
	+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	appointmentamount
	from (
   select  a."CreatedBy"  "AccountId",   
   case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
   case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal",
	case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
    case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
	case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
    case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
    case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"	
	from "Receipt" A
    join "Appointment" ap on  ap."AppointmentId" =A."RespectiveId"  
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
    and ap."Active" =true	
   where case when accountid is null then 1=1 else a."CreatedBy"=accountid end  and A."ReceiptTypeId"=1 	
	and A."Active"<>false and A."RespectiveId" is not null
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
	and coalesce(A."IsRefunded",false) <>true and ap."Status" <> 'C' and	
	case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end	
	)a 
	group by  a."AccountId"	 
)

,refundappointmentamount as (
	select a."AccountId" ,
	sum(A."CashTotal") "AppointmentRefCashTotal",
	sum(A."CardTotal") "AppointmentRefCardTotal",
	sum(A."UPITotal") "AppointmentRefUPITotal",
	sum(A."OnlineTotal") "AppointmentRefOnlineTotal",
	sum(A."ChequeTotal") "AppointmentRefChequeTotal",
	sum(A."PaytmTotal") "AppointmentRefPaytmTotal",
	sum(A."NotPaidTotal") "AppointmentRefNotPaidTotal",
	sum(A."OtherTotal") "AppointmentRefOtherTotal",
	sum(A."CardSwipeTotal") "AppointmentRefCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AppointmentRefCardStandAloneTotal",
	sum(A."CardUPITotal") "AppointmentRefCardUPITotal",
	sum(A."CardGpayTotal") "AppointmentRefCardGpayTotal",
	sum(A."CashDrawerTotal") "AppointmentRefCashDrawerTotal",
	sum(A."CashChequeTotal") "AppointmentRefCashChequeTotal",
	sum(A."CashDDTotal") "AppointmentRefCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AppointmentRefWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AppointmentRefWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AppointmentRefCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AppointmentRefWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	
	 refappointmentamount 
	from (
    select  a."CreatedBy"  "AccountId",
	 case when A."PayTypeId"=1 then coalesce(A."Cost",0) else 0 end  "CashTotal" ,
      case when A."PayTypeId"=2 then coalesce(A."Cost",0) else 0 end "CardTotal" ,
	 case when A."PayTypeId"=3 then coalesce(A."Cost",0) else 0 end  "UPITotal" ,
     case when A."PayTypeId"=4 then coalesce(A."Cost",0) else 0 end "OnlineTotal",
	case when A."PayTypeId"=5 then coalesce(A."Cost",0) else 0 end  "ChequeTotal" ,
    case when A."PayTypeId"=6 then coalesce(A."Cost",0) else 0 end "PaytmTotal",
   case when A."PayTypeId"=7 then coalesce(A."Cost",0) else 0 end "NotPaidTotal",
   case when A."PayTypeId"=8 then coalesce(A."Cost",0) else 0 end  "OtherTotal",
   case when A."PayTypeId"=9 then coalesce(A."Cost",0) else 0 end  "CardSwipeTotal",
   case when A."PayTypeId"=10 then coalesce(A."Cost",0) else 0 end  "CardStandAloneTotal",
   case when A."PayTypeId"=11 then coalesce(A."Cost",0) else 0 end "CardUPITotal",
   case when A."PayTypeId"=12 then coalesce(A."Cost",0) else 0 end  "CardGpayTotal",
   case when A."PayTypeId"=13 then coalesce(A."Cost",0) else 0 end  "CashDrawerTotal",
   case when A."PayTypeId"=14 then coalesce(A."Cost",0) else 0 end "CashChequeTotal",
   case when A."PayTypeId"=15 then coalesce(A."Cost",0) else 0 end "CashDDTotal",
   case when A."PayTypeId"=16 then coalesce(A."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
   case when A."PayTypeId"=17 then coalesce(A."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
   case when A."PayTypeId"=18 then coalesce(A."Cost",0) else 0 end  "CashRemoteDepositTotal",
   case when A."PayTypeId"=19 then coalesce(A."Cost",0) else 0 end   "WalletPaytmDQRTotal"
		 from "Receipt" A
    join "Appointment" ap on ap."AppointmentId" =A."RespectiveId"  
	join "Provider" pr on pr."ProviderId"= ap."ProviderId"
   and ap."Status" <> 'C'   and ap."Active" =true
	
   where case when accountid is null then 1=1 else a."CreatedBy"=accountid end   
	and A."Active"<>false and A."RespectiveId" is not null 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ap."LocationId"=locationId END 
	and coalesce(A."IsRefunded",false) = true and 
	case when "fromDate" is null then 1=1 
	else (A."CreatedDate"::date >= "fromDate" and A."CreatedDate"::date <= "toDate")  end
	) a
	group by  a."AccountId"	
	
)

,appointmentamount as (
select  A."AccountId",
	coalesce(A."AppointmentCashTotal",0) - coalesce(B."AppointmentRefCashTotal",0) as "AppointmentCashTotal" ,
	coalesce(A."AppointmentCardTotal",0) - coalesce(B."AppointmentRefCardTotal",0) as "AppointmentCardTotal" ,
	coalesce(A."AppointmentUPITotal",0) - coalesce(B."AppointmentRefUPITotal",0) as "AppointmentUPITotal" ,
	coalesce(A."AppointmentOnlineTotal",0) - coalesce(B."AppointmentRefOnlineTotal",0) as "AppointmentOnlineTotal" ,
	coalesce(A."AppointmentChequeTotal",0) - coalesce(B."AppointmentRefChequeTotal",0) as "AppointmentChequeTotal" ,
	coalesce(A."AppointmentPaytmTotal",0) - coalesce(B."AppointmentRefPaytmTotal",0) as "AppointmentPaytmTotal" ,
	coalesce(A."AppointmentNotPaidTotal",0) - coalesce(B."AppointmentRefNotPaidTotal",0) as "AppointmentNotPaidTotal" ,
	coalesce(A."AppointmentOtherTotal",0) - coalesce(B."AppointmentRefOtherTotal",0) as "AppointmentOtherTotal" ,
	coalesce(A."AppointmentCardSwipeTotal",0) - coalesce(B."AppointmentRefCardSwipeTotal",0) as "AppointmentCardSwipeTotal" ,
	coalesce(A."AppointmentCardStandAloneTotal",0) - coalesce(B."AppointmentRefCardStandAloneTotal",0) as "AppointmentCardStandAloneTotal" ,
	coalesce(A."AppointmentCardUPITotal",0) - coalesce(B."AppointmentRefCardUPITotal",0) as "AppointmentCardUPITotal" ,
	coalesce(A."AppointmentCardGpayTotal",0) - coalesce(B."AppointmentRefCardGpayTotal",0) as "AppointmentCardGpayTotal" ,
	coalesce(A."AppointmentCashDrawerTotal",0) - coalesce(B."AppointmentRefCashDrawerTotal",0) as "AppointmentCashDrawerTotal" ,
	coalesce(A."AppointmentCashChequeTotal",0) - coalesce(B."AppointmentRefCashChequeTotal",0) as "AppointmentCashChequeTotal" ,
	coalesce(A."AppointmentCashDDTotal",0) - coalesce(B."AppointmentRefCashDDTotal",0) as "AppointmentCashDDTotal" ,
	coalesce(A."AppointmentWalletPaytmOfflineTotal",0) - coalesce(B."AppointmentRefWalletPaytmOfflineTotal",0) as "AppointmentWalletPaytmOfflineTotal" ,
	coalesce(A."AppointmentWalletPhonePeOfflineTotal",0) - coalesce(B."AppointmentRefWalletPhonePeOfflineTotal",0) as "AppointmentWalletPhonePeOfflineTotal" ,
	coalesce(A."AppointmentCashRemoteDepositTotal",0) - coalesce(B."AppointmentRefCashRemoteDepositTotal",0) as "AppointmentCashRemoteDepositTotal" ,
		coalesce(A."AppointmentWalletPaytmDQRTotal",0) - coalesce(B."AppointmentRefWalletPaytmDQRTotal",0) as "AppointmentWalletPaytmDQRTotal" ,
	coalesce(A.appointmentamount,0) - coalesce(B.refappointmentamount,0) as "AppointmentAmount" from actappointmentamount A
	left join refundappointmentamount B on A."AccountId"=B."AccountId"
	
	
)

,actadmissionamount as (
	
	select a."AccountId" , 
	sum(A."CashTotal") "AdmissionCashTotal",
	sum(A."CardTotal") "AdmissionCardTotal",
	 sum(A."UPITotal") "AdmissionUPITotal",
	sum(A."OnlineTotal") "AdmissionOnlineTotal",
	 sum(A."ChequeTotal") "AdmissionChequeTotal",
	sum(A."PaytmTotal") "AdmissionPaytmTotal",
	sum(A."NotPaidTotal") "AdmissionNotPaidTotal",
	sum(A."OtherTotal") "AdmissionOtherTotal",
	sum(A."CardSwipeTotal") "AdmissionCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AdmissionCardStandAloneTotal",
	sum(A."CardUPITotal") "AdmissionCardUPITotal",
	sum(A."CardGpayTotal") "AdmissionCardGpayTotal",
	sum(A."CashDrawerTotal") "AdmissionCashDrawerTotal",
	sum(A."CashChequeTotal") "AdmissionCashChequeTotal",
	sum(A."CashDDTotal") "AdmissionCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AdmissionWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AdmissionWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AdmissionCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AdmissionWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")
	"AdmissionAmount"
	from (
select adr."CreatedBy" "AccountId" ,
     case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
     case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal"	,
	  case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
       case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal"	,	
       case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
       case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal"	,
       case when adr."PayTypeId"=7 then coalesce(adr."Cost",0) else 0 end "NotPaidTotal",
        case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end  "OtherTotal",
        case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardSwipeTotal",
        case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end  "CardStandAloneTotal",
        case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal",
        case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end  "CardGpayTotal",
        case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end  "CashDrawerTotal",
        case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
        case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
        case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
        case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
        case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end  "CashRemoteDepositTotal",
        case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end   "WalletPaytmDQRTotal"
												  
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when accountid is null then 1=1 else adr."CreatedBy"=accountid end 	
	and adr."ReceiptTypeId"=1  and adr."Active"<>false  and adr."AdmissionId" is not null
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	)a
	group by  a."AccountId"	
)

,refadmissionamount as (
	select a."AccountId" , 
	sum(A."CashTotal") "AdmissionRefCashTotal",
	sum(A."CardTotal") "AdmissionRefCardTotal",
	sum(A."UPITotal") "AdmissionRefUPITotal",
	sum(A."OnlineTotal") "AdmissionRefOnlineTotal",
	sum(A."ChequeTotal") "AdmissionRefChequeTotal",
	sum(A."PaytmTotal") "AdmissionRefPaytmTotal",
	sum(A."NotPaidTotal") "AdmissionRefNotPaidTotal",
	sum(A."OtherTotal") "AdmissionRefOtherTotal",
	sum(A."CardSwipeTotal") "AdmissionRefCardSwipeTotal",
	sum(A."CardStandAloneTotal") "AdmissionRefCardStandAloneTotal",
	sum(A."CardUPITotal") "AdmissionRefCardUPITotal",
	sum(A."CardGpayTotal") "AdmissionRefCardGpayTotal",
	sum(A."CashDrawerTotal") "AdmissionRefCashDrawerTotal",
	sum(A."CashChequeTotal") "AdmissionRefCashChequeTotal",
	sum(A."CashDDTotal") "AdmissionRefCashDDTotal",
	sum(A."WalletPaytmOfflineTotal") "AdmissionRefWalletPaytmOfflineTotal",
	sum(A."WalletPhonePeOfflineTotal") "AdmissionRefWalletPhonePeOfflineTotal",
	sum(A."CashRemoteDepositTotal") "AdmissionRefCashRemoteDepositTotal",
	sum(A."WalletPaytmDQRTotal") "AdmissionRefWalletPaytmDQRTotal",
	sum(A."CashTotal")+ sum(A."CardTotal")+ sum(A."UPITotal")+ sum(A."OnlineTotal")+ sum(A."ChequeTotal")+ sum(A."PaytmTotal")
	+sum(A."OtherTotal")+sum(A."CardSwipeTotal")+sum(A."CardStandAloneTotal")+sum(A."CardUPITotal")+sum(A."CardGpayTotal")+sum(A."CashDrawerTotal")+sum(A."CashChequeTotal")+sum(A."NotPaidTotal")+
	sum(A."CashDDTotal")+sum(A."WalletPaytmOfflineTotal")+sum(A."WalletPhonePeOfflineTotal")+sum(A."CashRemoteDepositTotal")+sum(A."WalletPaytmDQRTotal")

	"AdmissionRefAmount" 
	from (
select adr."CreatedBy" "AccountId"  ,  
		case when adr."PayTypeId"=1 then coalesce(adr."Cost",0) else 0 end  "CashTotal" ,
        case when adr."PayTypeId"=2 then coalesce(adr."Cost",0) else 0 end "CardTotal" ,
		case when adr."PayTypeId"=3 then coalesce(adr."Cost",0) else 0 end  "UPITotal" ,
        case when adr."PayTypeId"=4 then coalesce(adr."Cost",0) else 0 end "OnlineTotal" ,
		case when adr."PayTypeId"=5 then coalesce(adr."Cost",0) else 0 end  "ChequeTotal" ,
        case when adr."PayTypeId"=6 then coalesce(adr."Cost",0) else 0 end "PaytmTotal" ,
		case when adr."PayTypeId"=7 then coalesce(adr."Cost",0) else 0 end "NotPaidTotal",
        case when adr."PayTypeId"=8 then coalesce(adr."Cost",0) else 0 end  "OtherTotal",
        case when adr."PayTypeId"=9 then coalesce(adr."Cost",0) else 0 end  "CardSwipeTotal",
        case when adr."PayTypeId"=10 then coalesce(adr."Cost",0) else 0 end  "CardStandAloneTotal",
        case when adr."PayTypeId"=11 then coalesce(adr."Cost",0) else 0 end "CardUPITotal",
        case when adr."PayTypeId"=12 then coalesce(adr."Cost",0) else 0 end  "CardGpayTotal",
        case when adr."PayTypeId"=13 then coalesce(adr."Cost",0) else 0 end  "CashDrawerTotal",
        case when adr."PayTypeId"=14 then coalesce(adr."Cost",0) else 0 end "CashChequeTotal",
        case when adr."PayTypeId"=15 then coalesce(adr."Cost",0) else 0 end "CashDDTotal",
        case when adr."PayTypeId"=16 then coalesce(adr."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
        case when adr."PayTypeId"=17 then coalesce(adr."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
        case when adr."PayTypeId"=18 then coalesce(adr."Cost",0) else 0 end  "CashRemoteDepositTotal",
        case when adr."PayTypeId"=19 then coalesce(adr."Cost",0) else 0 end   "WalletPaytmDQRTotal"
from  "Receipt" adr 	 
	 join "Admission" ad on  adr."AdmissionId" = ad."AdmissionId" and ad."Active" <> false
	join "Provider" pr on pr."ProviderId"= ad."ProviderId"
	where case when accountid is null then 1=1 else adr."CreatedBy"=accountid end 	
	 and adr."IsRefunded" = true   and adr."Active"<>false  and adr."AdmissionId" is not null
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ad."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (adr."CreatedDate"::date >= "fromDate" and adr."CreatedDate"::date <= "toDate")  end	)a
	group by  a."AccountId"	
)

,admissionamount as (
select A."AccountId" ,
	coalesce(A."AdmissionCashTotal",0) - coalesce(B."AdmissionRefCashTotal",0) "AdmissionCashTotal",
	coalesce(A."AdmissionCardTotal",0) - coalesce(B."AdmissionRefCardTotal",0) "AdmissionCardTotal",
	coalesce(A."AdmissionUPITotal",0) - coalesce(B."AdmissionRefUPITotal",0) "AdmissionUPITotal",
	coalesce(A."AdmissionOnlineTotal",0) - coalesce(B."AdmissionRefOnlineTotal",0) "AdmissionOnlineTotal",
	coalesce(A."AdmissionChequeTotal",0) - coalesce(B."AdmissionRefChequeTotal",0) "AdmissionChequeTotal",
	coalesce(A."AdmissionPaytmTotal",0) - coalesce(B."AdmissionRefPaytmTotal",0) "AdmissionPaytmTotal",
	coalesce(A."AdmissionNotPaidTotal",0) - coalesce(B."AdmissionRefNotPaidTotal",0) as "AdmissionNotPaidTotal" ,
	coalesce(A."AdmissionOtherTotal",0) - coalesce(B."AdmissionRefOtherTotal",0) as "AdmissionOtherTotal" ,
	coalesce(A."AdmissionCardSwipeTotal",0) - coalesce(B."AdmissionRefCardSwipeTotal",0) as "AdmissionCardSwipeTotal" ,
	coalesce(A."AdmissionCardStandAloneTotal",0) - coalesce(B."AdmissionRefCardStandAloneTotal",0) as "AdmissionCardStandAloneTotal" ,
	coalesce(A."AdmissionCardUPITotal",0) - coalesce(B."AdmissionRefCardUPITotal",0) as "AdmissionCardUPITotal" ,
	coalesce(A."AdmissionCardGpayTotal",0) - coalesce(B."AdmissionRefCardGpayTotal",0) as "AdmissionCardGpayTotal" ,
	coalesce(A."AdmissionCashDrawerTotal",0) - coalesce(B."AdmissionRefCashDrawerTotal",0) as "AdmissionCashDrawerTotal" ,
	coalesce(A."AdmissionCashChequeTotal",0) - coalesce(B."AdmissionRefCashChequeTotal",0) as "AdmissionCashChequeTotal" ,
	coalesce(A."AdmissionCashDDTotal",0) - coalesce(B."AdmissionRefCashDDTotal",0) as "AdmissionCashDDTotal" ,
	coalesce(A."AdmissionWalletPaytmOfflineTotal",0) - coalesce(B."AdmissionRefWalletPaytmOfflineTotal",0) as "AdmissionWalletPaytmOfflineTotal" ,
	coalesce(A."AdmissionWalletPhonePeOfflineTotal",0) - coalesce(B."AdmissionRefWalletPhonePeOfflineTotal",0) as "AdmissionWalletPhonePeOfflineTotal" ,
	coalesce(A."AdmissionCashRemoteDepositTotal",0) - coalesce(B."AdmissionRefCashRemoteDepositTotal",0) as "AdmissionCashRemoteDepositTotal" ,
		coalesce(A."AdmissionWalletPaytmDQRTotal",0) - coalesce(B."AdmissionRefWalletPaytmDQRTotal",0) as "AdmissionWalletPaytmDQRTotal" ,
	coalesce(A."AdmissionAmount",0) - coalesce(B."AdmissionRefAmount",0) "AdmissionAmount"
   from actadmissionamount A
	left join refadmissionamount B on A."AccountId"=B."AccountId"	 

)
,LabAmount as ( 
select a."AccountId",
	sum(a."Cash") "LabCash",
	sum(a."Card") "LabCard" ,
	sum(a."UPI") "LabUPI",
	sum(a."Online") "LabOnline" ,
	sum(a."Cheque") "LabCheque",
	sum(a."Paytm") "LabPaytm" ,
	sum(a."NotPaidTotal") "LabNotPaidTotal",
	sum(a."OtherTotal") "LabOtherTotal",
	sum(a."CardSwipeTotal") "LabCardSwipeTotal",
	sum(a."CardStandAloneTotal") "LabCardStandAloneTotal",
	sum(a."CardUPITotal") "LabCardUPITotal",
	sum(a."CardGpayTotal") "LabCardGpayTotal",
	sum(a."CashDrawerTotal") "LabCashDrawerTotal",
	sum(a."CashChequeTotal") "LabCashChequeTotal",
	sum(a."CashDDTotal") "LabCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "LabWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "LabWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "LabCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "LabWalletPaytmDQRTotal",
	sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")

	"LabAmount"
	from(
select 	a."AccountId",							  
	case when ar."PayTypeId"=1 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cash",
	case when ar."PayTypeId"=2 then  coalesce(ar."OverallNetAmount",0) else 0 end "Card",
	case when ar."PayTypeId"=3 then  coalesce(ar."OverallNetAmount",0) else 0 end "UPI",
	case when ar."PayTypeId"=4 then  coalesce(ar."OverallNetAmount",0) else 0 end "Online",
	case when ar."PayTypeId"=5 then  coalesce(ar."OverallNetAmount",0) else 0 end "Cheque",
	case when ar."PayTypeId"=6 then  coalesce(ar."OverallNetAmount",0) else 0 end "Paytm",
	case when ar."PayTypeId"=7 then coalesce(ar."OverallNetAmount",0) else 0 end "NotPaidTotal",
    case when ar."PayTypeId"=8 then coalesce(ar."OverallNetAmount",0) else 0 end  "OtherTotal",
    case when ar."PayTypeId"=9 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardSwipeTotal",
    case when ar."PayTypeId"=10 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardStandAloneTotal",
    case when ar."PayTypeId"=11 then coalesce(ar."OverallNetAmount",0) else 0 end "CardUPITotal",
    case when ar."PayTypeId"=12 then coalesce(ar."OverallNetAmount",0) else 0 end  "CardGpayTotal",
    case when ar."PayTypeId"=13 then coalesce(ar."OverallNetAmount",0) else 0 end  "CashDrawerTotal",
    case when ar."PayTypeId"=14 then coalesce(ar."OverallNetAmount",0) else 0 end "CashChequeTotal",
    case when ar."PayTypeId"=15 then coalesce(ar."OverallNetAmount",0) else 0 end "CashDDTotal",
    case when ar."PayTypeId"=16 then coalesce(ar."OverallNetAmount",0) else 0 end  "WalletPaytmOfflineTotal",
    case when ar."PayTypeId"=17 then coalesce(ar."OverallNetAmount",0) else 0 end  "WalletPhonePeOfflineTotal",
    case when ar."PayTypeId"=18 then coalesce(ar."OverallNetAmount",0) else 0 end  "CashRemoteDepositTotal",
    case when ar."PayTypeId"=19 then coalesce(ar."OverallNetAmount",0) else 0 end   "WalletPaytmDQRTotal"
from "Account" a		
join "NewLabBookingHeader" ar on ar."CreatedBy" = a."AccountId" and ar."Active" <> false
where case when accountid is null then 1=1 else a."AccountId"=accountid end 
	AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ar."LocationId"=locationId END 
	and case when "fromDate" is null then 1=1 
	else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end)a
group by a."AccountId" )

,ScanAmount as (
	select s."AccountId",
	sum(s."Cash") "ScanCash",
	sum(s."Card") "ScanCard" ,
	sum(s."UPI") "ScanUPI",
	sum(s."Online") "ScanOnline" ,
	sum(s."Cheque") "ScanCheque",
	sum(s."Paytm") "ScanPaytm" ,
	sum(s."NotPaidTotal") "ScanNotPaidTotal",
	sum(s."OtherTotal") "ScanOtherTotal",
	sum(s."CardSwipeTotal") "ScanCardSwipeTotal",
	sum(s."CardStandAloneTotal") "ScanCardStandAloneTotal",
	sum(s."CardUPITotal") "ScanCardUPITotal",
	sum(s."CardGpayTotal") "ScanCardGpayTotal",
	sum(s."CashDrawerTotal") "ScanCashDrawerTotal",
	sum(s."CashChequeTotal") "ScanCashChequeTotal",
	sum(s."CashDDTotal") "ScanCashDDTotal",
	sum(s."WalletPaytmOfflineTotal") "ScanWalletPaytmOfflineTotal",
	sum(s."WalletPhonePeOfflineTotal") "ScanWalletPhonePeOfflineTotal",
	sum(s."CashRemoteDepositTotal") "ScanCashRemoteDepositTotal",
	sum(s."WalletPaytmDQRTotal") "ScanWalletPaytmDQRTotal",
	sum(s."Cash")+ sum(s."Card")+ sum(s."UPI")+ sum(s."Online")+ sum(s."Cheque")+ sum(s."Paytm")
	+sum(s."OtherTotal")+sum(s."CardSwipeTotal")+sum(s."CardStandAloneTotal")+sum(s."CardUPITotal")+sum(s."CardGpayTotal")+sum(s."CashDrawerTotal")+sum(s."CashChequeTotal")+sum(s."NotPaidTotal")+
	sum(s."CashDDTotal")+sum(s."WalletPaytmOfflineTotal")+sum(s."WalletPhonePeOfflineTotal")+sum(s."CashRemoteDepositTotal")+sum(s."WalletPaytmDQRTotal") "ScanAmount"
	from(
select 	a."AccountId",					  
	case when bsa."PayTypeId"=1  then coalesce(r."Cost",0) else 0 end "Cash",
	case when bsa."PayTypeId"=2  then coalesce(r."Cost",0) else 0 end "Card",
	case when bsa."PayTypeId"=3  then coalesce(r."Cost",0) else 0 end "UPI",
	case when bsa."PayTypeId"=4  then coalesce(r."Cost",0) else 0 end "Online",
	case when bsa."PayTypeId"=5  then coalesce(r."Cost",0) else 0 end "Cheque",
	case when bsa."PayTypeId"=6  then coalesce(r."Cost",0) else 0 end "Paytm",
	case when bsa."PayTypeId"=7  then coalesce(r."Cost",0) else 0 end "NotPaidTotal",
    case when bsa."PayTypeId"=8  then coalesce(r."Cost",0) else 0 end "OtherTotal",
    case when bsa."PayTypeId"=9  then coalesce(r."Cost",0) else 0 end "CardSwipeTotal",
    case when bsa."PayTypeId"=10 then coalesce(r."Cost",0) else 0 end "CardStandAloneTotal",
    case when bsa."PayTypeId"=11 then coalesce(r."Cost",0) else 0 end "CardUPITotal",
    case when bsa."PayTypeId"=12 then coalesce(r."Cost",0) else 0 end "CardGpayTotal",
    case when bsa."PayTypeId"=13 then coalesce(r."Cost",0) else 0 end "CashDrawerTotal",
    case when bsa."PayTypeId"=14 then coalesce(r."Cost",0) else 0 end "CashChequeTotal",
    case when bsa."PayTypeId"=15 then coalesce(r."Cost",0) else 0 end "CashDDTotal",
    case when bsa."PayTypeId"=16 then coalesce(r."Cost",0) else 0 end "WalletPaytmOfflineTotal",
    case when bsa."PayTypeId"=17 then coalesce(r."Cost",0) else 0 end "WalletPhonePeOfflineTotal",
    case when bsa."PayTypeId"=18 then coalesce(r."Cost",0) else 0 end "CashRemoteDepositTotal",
    case when bsa."PayTypeId"=19 then coalesce(r."Cost",0) else 0 end "WalletPaytmDQRTotal"
from "Account" a		
join "BookScanAppointment" bsa on bsa."CreatedBy" = a."AccountId" and bsa."Active" <> false
join "Receipt" r on r."CreatedBy" = a."AccountId" and r."Active" <> false
where R."RespectiveId" = bsa."BookScanAppointmentId" and R."ReceiptAreaTypeId"=10 and 
	  case when accountid is null then 1=1 else a."AccountId"=accountid end and
	  case when (locationId is null or locationId=0) then 1=1 else bsa."LocationId"=locationId end and
	  case when "fromDate" is null then 1=1 else (bsa."CreatedDate"::date >= "fromDate" and bsa."CreatedDate"::date <= "toDate") end	
	)s group by s."AccountId"
)	
	
,PharmaSaleAmount as (	
select a."AccountId", sum(a."Cash") "PharmaSaleCash",
	sum(a."Card") "PharmaSaleCard" ,
	sum(a."UPI") "PharmaSaleUPI",
	sum(a."Online") "PharmaSaleOnline" ,
	sum(a."Cheque") "PharmaSaleCheque",
	sum(a."Paytm") "PharmaSalePaytm" ,
	sum(a."NotPaidTotal") "PharmaSaleNotPaidTotal",
	sum(a."OtherTotal") "PharmaSaleOtherTotal",
	sum(a."CardSwipeTotal") "PharmaSaleCardSwipeTotal",
	sum(a."CardStandAloneTotal") "PharmaSaleCardStandAloneTotal",
	sum(a."CardUPITotal") "PharmaSaleCardUPITotal",
	sum(a."CardGpayTotal") "PharmaSaleCardGpayTotal",
	sum(a."CashDrawerTotal") "PharmaSaleCashDrawerTotal",
	sum(a."CashChequeTotal") "PharmaSaleCashChequeTotal",
	sum(a."CashDDTotal") "PharmaSaleCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "PharmaSaleWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "PharmaSaleWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "PharmaSaleCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "PharmaSaleWalletPaytmDQRTotal",
	 sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")

	"PharmaSaleAmount" 
	from (
select a."AccountId", 
	 case when ar."PayTypeId"=1 then  coalesce(ar."Cost",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."Cost",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."Cost",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."Cost",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."Cost",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."Cost",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."Cost",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."Cost",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."Cost",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."Cost",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."Cost",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."Cost",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."Cost",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."Cost",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."Cost",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."Cost",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."Cost",0) else 0 end   "WalletPaytmDQRTotal"
from "Account" a
join "Receipt" ar on ar."CreatedBy" = a."AccountId" and ar."ReceiptAreaTypeId"=1
join "PharmacySaleHeader" ps on ps."PharmacySaleHeaderId"=ar."RespectiveId"
where case when accountid is null then 1=1 else a."AccountId"=accountid end
		AND CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE ps."LocationId"=locationId END 
		and case when "fromDate" is null then 1=1 
else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end	
	)a
group by a."AccountId"
)
,PharmaReturnAmount as (
select a."AccountId", 
	sum(a."Cash") "PharmaReturnCash",
	sum(a."Card") "PharmaReturnCard" ,
	sum(a."UPI") "PharmaReturnUPI",
	sum(a."Online") "PharmaReturnOnline" ,
	sum(a."Cheque") "PharmaReturnCheque",
	sum(a."Paytm") "PharmaReturnPaytm" ,
	sum(a."NotPaidTotal") "PharmaReturnNotPaidTotal",
	sum(a."OtherTotal") "PharmaReturnOtherTotal",
	sum(a."CardSwipeTotal") "PharmaReturnCardSwipeTotal",
	sum(a."CardStandAloneTotal") "PharmaReturnCardStandAloneTotal",
	sum(a."CardUPITotal") "PharmaReturnCardUPITotal",
	sum(a."CardGpayTotal") "PharmaReturnCardGpayTotal",
	sum(a."CashDrawerTotal") "PharmaReturnCashDrawerTotal",
	sum(a."CashChequeTotal") "PharmaReturnCashChequeTotal",
	sum(a."CashDDTotal") "PharmaReturnCashDDTotal",
	sum(a."WalletPaytmOfflineTotal") "PharmaReturnWalletPaytmOfflineTotal",
	sum(a."WalletPhonePeOfflineTotal") "PharmaReturnWalletPhonePeOfflineTotal",
	sum(a."CashRemoteDepositTotal") "PharmaReturnCashRemoteDepositTotal",
	sum(a."WalletPaytmDQRTotal") "PharmaReturnWalletPaytmDQRTotal",
	 sum(a."Cash")+ sum(a."Card")+ sum(a."UPI")+ sum(a."Online")+ sum(a."Cheque")+ sum(a."Paytm")
	+sum(a."OtherTotal")+sum(a."CardSwipeTotal")+sum(a."CardStandAloneTotal")+sum(a."CardUPITotal")+sum(a."CardGpayTotal")+sum(a."CashDrawerTotal")+sum(a."CashChequeTotal")+sum(a."NotPaidTotal")+
	sum(a."CashDDTotal")+sum(a."WalletPaytmOfflineTotal")+sum(a."WalletPhonePeOfflineTotal")+sum(a."CashRemoteDepositTotal")+sum(a."WalletPaytmDQRTotal")
 
	"PharmaReturnAmount"
	from(
select a."AccountId", 
	 case when ar."PayTypeId"=1 then  coalesce(ar."Cost",0) else 0 end "Cash"
	,case when ar."PayTypeId"=2 then  coalesce(ar."Cost",0) else 0 end "Card"
	,case when ar."PayTypeId"=3 then  coalesce(ar."Cost",0) else 0 end "UPI"
	,case when ar."PayTypeId"=4 then  coalesce(ar."Cost",0) else 0 end "Online"
	,case when ar."PayTypeId"=5 then  coalesce(ar."Cost",0) else 0 end "Cheque"
	,case when ar."PayTypeId"=6 then  coalesce(ar."Cost",0) else 0 end "Paytm",
	 case when ar."PayTypeId"=7 then coalesce(ar."Cost",0) else 0 end "NotPaidTotal",
     case when ar."PayTypeId"=8 then coalesce(ar."Cost",0) else 0 end  "OtherTotal",
     case when ar."PayTypeId"=9 then coalesce(ar."Cost",0) else 0 end  "CardSwipeTotal",
     case when ar."PayTypeId"=10 then coalesce(ar."Cost",0) else 0 end  "CardStandAloneTotal",
      case when ar."PayTypeId"=11 then coalesce(ar."Cost",0) else 0 end "CardUPITotal",
      case when ar."PayTypeId"=12 then coalesce(ar."Cost",0) else 0 end  "CardGpayTotal",
      case when ar."PayTypeId"=13 then coalesce(ar."Cost",0) else 0 end  "CashDrawerTotal",
       case when ar."PayTypeId"=14 then coalesce(ar."Cost",0) else 0 end "CashChequeTotal",
       case when ar."PayTypeId"=15 then coalesce(ar."Cost",0) else 0 end "CashDDTotal",
       case when ar."PayTypeId"=16 then coalesce(ar."Cost",0) else 0 end  "WalletPaytmOfflineTotal",
       case when ar."PayTypeId"=17 then coalesce(ar."Cost",0) else 0 end  "WalletPhonePeOfflineTotal",
       case when ar."PayTypeId"=18 then coalesce(ar."Cost",0) else 0 end  "CashRemoteDepositTotal",
       case when ar."PayTypeId"=19 then coalesce(ar."Cost",0) else 0 end   "WalletPaytmDQRTotal"
		
							   
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"
left join "Receipt" ar on ar."CreatedBy" = a."AccountId" and ar."ReceiptAreaTypeId"=7
left join "SaleReturnHeader" sh on sh."SaleReturnHeaderId" = ar."RespectiveId"
where case when accountid is null then 1=1 else ar."CreatedBy"=accountid end 
	AND   CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE LAM."LocationId"=locationId END
	and case when "fromDate" is null then 1=1 
else (ar."CreatedDate"::date >= "fromDate" and ar."CreatedDate"::date <= "toDate")  end	
	)a
group by a."AccountId"
)

 ,PharmaAmount as (
 select a."AccountId", 	
 	 coalesce(a."PharmaSaleCash",0) - coalesce(b."PharmaReturnCash",0) as  "PharmaSaleCash" ,
	 coalesce(a."PharmaSaleCard",0) - coalesce(b."PharmaReturnCard",0) as  "PharmaSaleCard" ,
	 coalesce(a."PharmaSaleUPI",0) - coalesce(b."PharmaReturnUPI",0) as  "PharmaSaleUPI" ,
	 coalesce(a."PharmaSaleOnline",0) - coalesce(b."PharmaReturnOnline",0) as  "PharmaSaleOnline" ,
	 coalesce(a."PharmaSaleCheque",0) - coalesce(b."PharmaReturnCheque",0) as  "PharmaSaleCheque" ,
	 coalesce(a."PharmaSalePaytm",0) - coalesce(b."PharmaReturnPaytm",0) as  "PharmaSalePaytm" ,
	 coalesce(a."PharmaSaleNotPaidTotal",0) - coalesce(b."PharmaReturnNotPaidTotal",0) as  "PharmaSaleNotPaidTotal" ,
	 coalesce(a."PharmaSaleOtherTotal",0) - coalesce(b."PharmaReturnOtherTotal",0) as  "PharmaSaleOtherTotal" ,
	 coalesce(a."PharmaSaleCardSwipeTotal",0) - coalesce(b."PharmaReturnCardSwipeTotal",0) as  "PharmaSaleCardSwipeTotal" ,
	 coalesce(a."PharmaSaleCardStandAloneTotal",0) - coalesce(b."PharmaReturnCardStandAloneTotal",0) as  "PharmaSaleCardStandAloneTotal" ,
	 coalesce(a."PharmaSaleCardUPITotal",0) - coalesce(b."PharmaReturnCardUPITotal",0) as  "PharmaSaleCardUPITotal" ,
	 coalesce(a."PharmaSaleCardGpayTotal",0) - coalesce(b."PharmaReturnCardGpayTotal",0) as  "PharmaSaleCardGpayTotal" ,
	 coalesce(a."PharmaSaleCashDrawerTotal",0) - coalesce(b."PharmaReturnCashDrawerTotal",0) as  "PharmaSaleCashDrawerTotal" ,
	 coalesce(a."PharmaSaleCashDDTotal",0) - coalesce(b."PharmaReturnCashDDTotal",0) as  "PharmaSaleCashDDTotal" ,
	 coalesce(a."PharmaSaleCashChequeTotal",0) - coalesce(b."PharmaReturnCashChequeTotal",0) as  "PharmaSaleCashChequeTotal" ,
	 coalesce(a."PharmaSaleWalletPaytmOfflineTotal",0) - coalesce(b."PharmaReturnWalletPaytmOfflineTotal",0) as  "PharmaSaleWalletPaytmOfflineTotal" ,
	 coalesce(a."PharmaSaleWalletPhonePeOfflineTotal",0) - coalesce(b."PharmaReturnWalletPhonePeOfflineTotal",0) as  "PharmaSaleWalletPhonePeOfflineTotal" ,
	 coalesce(a."PharmaSaleCashRemoteDepositTotal",0) - coalesce(b."PharmaReturnCashRemoteDepositTotal",0) as  "PharmaSaleCashRemoteDepositTotal" ,
	 coalesce(a."PharmaSaleWalletPaytmDQRTotal",0) - coalesce(b."PharmaReturnWalletPaytmDQRTotal",0) as  "PharmaSaleWalletPaytmDQRTotal" ,
	coalesce(a."PharmaSaleAmount",0) - coalesce(b."PharmaReturnAmount",0) as  "PharmaAmount" 
 from PharmaSaleAmount a
 	left join PharmaReturnAmount b on a."AccountId"=b."AccountId"
 )
 
select distinct  a."AccountId",a."EmployeeName",a."RoleName",
                     pr."RegistrationCashTotal",pr."RegistrationCardTotal",pr."RegistrationUPITotal",pr."RegistrationOnlineTotal",pr."RegistrationChequeTotal",pr."RegistrationPaytmTotal",
						 pr.  "RegistrationNotPaidTotal" ,pr. "RegistrationOtherTotal" ,pr. "RegistrationCardSwipeTotal" ,pr."RegistrationCardStandAloneTotal" ,
				    pr. "RegistrationCardUPITotal" ,pr."RegistrationCardGpayTotal" ,pr."RegistrationCashDrawerTotal" ,pr."RegistrationCashChequeTotal" ,
				    pr. "RegistrationCashDDTotal" ,pr."RegistrationWalletPaytmOfflineTotal" ,pr."RegistrationWalletPhonePeOfflineTotal" ,pr."RegistrationCashRemoteDepositTotal" ,
				      pr. "RegistrationWalletPaytmDQRTotal" ,
						pr."registrationamount",
						  ap."AppointmentCashTotal",ap."AppointmentCardTotal",ap."AppointmentUPITotal",ap."AppointmentOnlineTotal",ap."AppointmentChequeTotal",ap."AppointmentPaytmTotal",
						 ap."AppointmentNotPaidTotal" ,ap."AppointmentOtherTotal" ,ap."AppointmentCardSwipeTotal" ,ap."AppointmentCardStandAloneTotal" ,
				   ap."AppointmentCardUPITotal" ,ap."AppointmentCardGpayTotal" ,ap."AppointmentCashDrawerTotal" ,ap."AppointmentCashChequeTotal" ,
				    ap."AppointmentCashDDTotal" ,ap."AppointmentWalletPaytmOfflineTotal" ,ap."AppointmentWalletPhonePeOfflineTotal" ,ap."AppointmentCashRemoteDepositTotal" ,
				     ap."AppointmentWalletPaytmDQRTotal" ,
						ap."AppointmentAmount",
						  ad."AdmissionCashTotal",ad."AdmissionCardTotal",ad."AdmissionUPITotal",ad."AdmissionOnlineTotal",ad."AdmissionChequeTotal",ad."AdmissionPaytmTotal",
						 ad."AdmissionCardUPITotal" ,ad."AdmissionCardGpayTotal" ,ad."AdmissionCashDrawerTotal" ,ad."AdmissionCashChequeTotal" ,
						 ad."AdmissionNotPaidTotal" ,ad."AdmissionOtherTotal" ,ad."AdmissionCardSwipeTotal" ,ad."AdmissionCardStandAloneTotal" ,
				    ad."AdmissionCashDDTotal" ,ad."AdmissionWalletPaytmOfflineTotal" ,ad."AdmissionWalletPhonePeOfflineTotal" ,ad."AdmissionCashRemoteDepositTotal" ,
				     ad."AdmissionWalletPaytmDQRTotal" , 
						ad."AdmissionAmount",
						  lb."LabCash", lb."LabCard",lb."LabUPI", lb."LabOnline",lb."LabCheque", lb."LabPaytm",
						    lb."LabNotPaidTotal" , lb."LabOtherTotal" , lb."LabCardSwipeTotal" , lb."LabCardStandAloneTotal" ,
						 lb."LabCardUPITotal" ,lb."LabCardGpayTotal" ,lb."LabCashDrawerTotal" ,lb."LabCashChequeTotal" ,
				   lb."LabCashDDTotal" ,lb."LabWalletPaytmOfflineTotal" ,lb."LabWalletPhonePeOfflineTotal" ,lb."LabCashRemoteDepositTotal" ,
				     lb."LabWalletPaytmDQRTotal" 
						,lb."LabAmount",
						
				sa."ScanCash", sa."ScanCard", sa."ScanUPI", sa."ScanOnline", sa."ScanCheque", sa."ScanPaytm",
				sa."ScanNotPaidTotal", sa."ScanOtherTotal", sa."ScanCardSwipeTotal", sa."ScanCardStandAloneTotal",
				sa."ScanCardUPITotal", sa."ScanCardGpayTotal", sa."ScanCashDrawerTotal", sa."ScanCashChequeTotal",
				sa."ScanCashDDTotal" ,sa."ScanWalletPaytmOfflineTotal" ,sa."ScanWalletPhonePeOfflineTotal",
				sa."ScanCashRemoteDepositTotal", sa."ScanWalletPaytmDQRTotal", sa."ScanAmount",
				
sum(pa."PharmaSaleCash") over(partition by a."AccountId")  "PharmacySaleCash",
sum(pa."PharmaSaleCard") over(partition by a."AccountId") 	"PharmacySaleCard",
sum(pa."PharmaSaleUPI") over(partition by a."AccountId")  "PharmacySaleUPI",
sum(pa."PharmaSaleOnline") over(partition by a."AccountId") 	"PharmacySaleOnline",
sum(pa."PharmaSaleCheque") over(partition by a."AccountId")  "PharmacySaleCheque",
sum(pa."PharmaSalePaytm") over(partition by a."AccountId") 	"PharmacySalePaytm",
sum(pa."PharmaSaleNotPaidTotal") over(partition by a."AccountId") 	"PharmacySaleNotPaidTotal",
sum(pa."PharmaSaleOtherTotal") over(partition by a."AccountId") 	"PharmacySaleOtherTotal",
sum(pa."PharmaSaleCardSwipeTotal") over(partition by a."AccountId") 	"PharmacySaleCardSwipeTotal",
sum(pa."PharmaSaleCardStandAloneTotal") over(partition by a."AccountId") 	"PharmacySaleCardStandAloneTotal",
sum(pa."PharmaSaleCardUPITotal") over(partition by a."AccountId") 	"PharmacySaleCardUPITotal",
sum(pa."PharmaSaleCardGpayTotal") over(partition by a."AccountId") 	"PharmacySaleCardGpayTotal",
sum(pa."PharmaSaleCashDrawerTotal") over(partition by  a."AccountId") 	"PharmacySaleCashDrawerTotal",
sum(pa."PharmaSaleCashChequeTotal") over(partition by a."AccountId") 	"PharmacySaleCashChequeTotal",
sum(pa."PharmaSaleCashDDTotal") over(partition by a."AccountId") 	"PharmacySaleCashDDTotal",
sum(pa."PharmaSaleWalletPaytmOfflineTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPaytmOfflineTotal",
sum(pa."PharmaSaleWalletPhonePeOfflineTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPhonePeOfflineTotal",
sum(pa."PharmaSaleCashRemoteDepositTotal") over(partition by a."AccountId") 	"PharmacySaleCashRemoteDepositTotal",
sum(pa."PharmaSaleWalletPaytmDQRTotal") over(partition by a."AccountId") 	"PharmacySaleWalletPaytmDQRTotal",
sum(pa."PharmaAmount") over(partition by a."AccountId") "PharmacyAmount",
coalesce(pr."RegistrationCashTotal",0)+coalesce(ap."AppointmentCashTotal",0)+coalesce(ad."AdmissionCashTotal",0)+coalesce(lb."LabCash",0)+coalesce(sa."ScanCash",0)+coalesce(sum(pa."PharmaSaleCash") over(partition by a."AccountId") ,0) "TotalCash",
coalesce(pr."RegistrationCardTotal",0)+	coalesce(ap."AppointmentCardTotal",0)+coalesce(ad."AdmissionCardTotal",0)+coalesce(lb."LabCard",0)+coalesce(sa."ScanCard",0)+coalesce(sum(pa."PharmaSaleCard") over(partition by a."AccountId"),0)  "TotalCard",	
coalesce(pr."RegistrationUPITotal",0)+	coalesce(ap."AppointmentUPITotal",0)+coalesce(ad."AdmissionUPITotal",0)+coalesce(lb."LabUPI",0)+coalesce(sa."ScanUPI",0)+coalesce(sum(pa."PharmaSaleUPI") over(partition by a."AccountId") ,0) "TotalUPI",
coalesce(pr."RegistrationOnlineTotal",0)+coalesce(ap."AppointmentOnlineTotal",0)+coalesce(ad."AdmissionOnlineTotal",0)+coalesce(lb."LabOnline",0)+coalesce(sa."ScanOnline",0)+coalesce(sum(pa."PharmaSaleOnline") over(partition by a."AccountId"),0)  "TotalOnline",	
coalesce(pr."RegistrationChequeTotal",0)+coalesce(ap."AppointmentChequeTotal",0)+	coalesce(ad."AdmissionChequeTotal",0)+coalesce(lb."LabCheque",0)+coalesce(sa."ScanCheque",0)+coalesce(sum(pa."PharmaSaleCheque") over(partition by a."AccountId") ,0) "TotalCheque",
coalesce(pr."RegistrationPaytmTotal",0)+coalesce(ap."AppointmentPaytmTotal",0)+	coalesce(ad."AdmissionPaytmTotal",0)+coalesce(lb."LabPaytm",0)+coalesce(sa."ScanPaytm",0)+coalesce(sum(pa."PharmaSalePaytm") over(partition by a."AccountId"),0)  "TotalPaytm",	
coalesce(pr."RegistrationNotPaidTotal",0)+coalesce(ap."AppointmentPaytmTotal",0)+coalesce(ad."AdmissionNotPaidTotal",0)+coalesce(lb."LabNotPaidTotal",0)+coalesce(sa."ScanNotPaidTotal",0)+coalesce(sum(pa."PharmaSaleNotPaidTotal") over(partition by a."AccountId"),0)  "TotalNotPaid",
coalesce(pr."RegistrationOtherTotal",0)+coalesce(ap."AppointmentOtherTotal",0)+	coalesce(ad."AdmissionOtherTotal",0)+coalesce(lb."LabOtherTotal",0)+coalesce(sa."ScanOtherTotal",0)+coalesce(sum(pa."PharmaSaleOtherTotal") over(partition by a."AccountId"),0)  "TotalOther",
coalesce(pr."RegistrationCardSwipeTotal",0)+coalesce(ap."AppointmentCardSwipeTotal",0)+	coalesce(ad."AdmissionCardSwipeTotal",0)+coalesce(lb."LabCardSwipeTotal",0)+coalesce(sa."ScanCardSwipeTotal",0)+coalesce(sum(pa."PharmaSaleCardSwipeTotal") over(partition by a."AccountId"),0)  "CardSwipeTotal",
coalesce(pr."RegistrationCardStandAloneTotal",0)+coalesce(ap."AppointmentCardStandAloneTotal",0)+coalesce(ad."AdmissionCardStandAloneTotal",0)+coalesce(lb."LabCardStandAloneTotal",0)+coalesce(sa."ScanCardStandAloneTotal",0)+coalesce(sum(pa."PharmaSaleCardStandAloneTotal") over(partition by a."AccountId"),0)  "CardStandAloneTotal",
coalesce(pr."RegistrationCardUPITotal",0)+coalesce(ap."AppointmentCardUPITotal",0)+coalesce(ad."AdmissionCardUPITotal",0)+coalesce(lb."LabCardUPITotal",0)+coalesce(sa."ScanCardUPITotal",0)+coalesce(sum(pa."PharmaSaleCardUPITotal") over(partition by a."AccountId"),0)  "CardUPITotal",
coalesce(pr."RegistrationCardGpayTotal",0)+coalesce(ap."AppointmentCardGpayTotal",0)+coalesce(ad."AdmissionCardGpayTotal",0)+coalesce(lb."LabCardGpayTotal",0)+coalesce(sa."ScanCardGpayTotal",0)+coalesce(sum(pa."PharmaSaleCardGpayTotal") over(partition by a."AccountId"),0)  "CardGpayTotal",
coalesce(pr."RegistrationCashDrawerTotal",0)+coalesce(ap."AppointmentCashDrawerTotal",0)+coalesce(ad."AdmissionCashDrawerTotal",0)+coalesce(lb."LabCashDrawerTotal",0)+coalesce(sa."ScanCashDrawerTotal",0)+coalesce(sum(pa."PharmaSaleCashDrawerTotal") over(partition by a."AccountId"),0)  "CashDrawerTotal",
coalesce(pr."RegistrationCashChequeTotal",0)+coalesce(ap."AppointmentCashChequeTotal",0)+coalesce(ad."AdmissionCashChequeTotal",0)+coalesce(lb."LabCashChequeTotal",0)+coalesce(sa."ScanCashChequeTotal",0)+coalesce(sum(pa."PharmaSaleCashChequeTotal") over(partition by a."AccountId"),0) "CashChequeTotal",
coalesce(pr."RegistrationCashDDTotal",0)+coalesce(ap."AppointmentCashDDTotal",0)+coalesce(ad."AdmissionCashDDTotal",0)+coalesce(lb."LabCashDDTotal",0)+coalesce(sa."ScanCashDDTotal",0)+coalesce(sum(pa."PharmaSaleCashDDTotal") over(partition by a."AccountId"),0)  "CashDDTotal",
coalesce(pr."RegistrationWalletPaytmOfflineTotal",0)+coalesce(ap."AppointmentWalletPaytmOfflineTotal",0)+coalesce(ad."AdmissionWalletPaytmOfflineTotal",0)+coalesce(lb."LabWalletPaytmOfflineTotal",0)+coalesce(sa."ScanWalletPaytmOfflineTotal",0)+coalesce(sum(pa."PharmaSaleWalletPaytmOfflineTotal")over(partition by a."AccountId"),0)  "WalletPaytmOfflineTotal",
coalesce(ap."AppointmentWalletPhonePeOfflineTotal",0)+coalesce(ap."AppointmentWalletPhonePeOfflineTotal",0)+coalesce(ad."AdmissionWalletPhonePeOfflineTotal",0)+coalesce(lb."LabWalletPhonePeOfflineTotal",0)+coalesce(sa."ScanWalletPhonePeOfflineTotal",0)+coalesce(sum(pa."PharmaSaleWalletPhonePeOfflineTotal") over(partition by a."AccountId"),0)  "WalletPhonePeOfflineTotal",
coalesce(pr."RegistrationCashRemoteDepositTotal",0)+coalesce(ap."AppointmentCashRemoteDepositTotal",0)+	coalesce(ad."AdmissionCashRemoteDepositTotal",0)+coalesce(lb."LabCashRemoteDepositTotal",0)+coalesce(sa."ScanCashRemoteDepositTotal",0)+coalesce(sum(pa."PharmaSaleCashRemoteDepositTotal")over(partition by a."AccountId"),0)  "CashRemoteDepositTotal",
coalesce(pr."RegistrationWalletPaytmDQRTotal",0)+coalesce(ap."AppointmentWalletPaytmDQRTotal",0)+coalesce(ad."AdmissionWalletPaytmDQRTotal",0)+coalesce(lb."LabWalletPaytmDQRTotal",0)+coalesce(sa."ScanWalletPaytmDQRTotal",0)+coalesce(sum(pa."PharmaSaleWalletPaytmDQRTotal") over(partition by a."AccountId"),0)  "WalletPaytmDQRTotal",
coalesce(pr."registrationamount",0)+coalesce(ap."AppointmentAmount",0)+coalesce(ad."AdmissionAmount",0)+coalesce(lb."LabAmount",0)+coalesce(sa."ScanAmount",0)
+coalesce(sum(pa."PharmaAmount") over(partition by a."AccountId"),0) "Total"

from accountdata a

left join patientRegistrationamount pr on pr."AccountId"=a."AccountId"
left join appointmentamount ap on ap."AccountId"=a."AccountId"
left join admissionamount ad on ad."AccountId"=a."AccountId"
left join LabAmount lb on lb."AccountId"=a."AccountId"
left join ScanAmount sa on sa."AccountId"=a."AccountId"
left join PharmaAmount pa on pa."AccountId"=a."AccountId"
;
	end
$BODY$;
---------------------------------------------------------------Chandana 21Sep2023------------------------------------------------------------------------------
alter table if exists  "DietEncounter" 
add column if not exists "PatientId" int REFERENCES "Patient"("PatientId");

---------------------------------------------------------------Chandana 21Sep2023------------------------------------------------------------------------------
alter table if exists "MasterBill"
add column if not exists "RemovedAmount" numeric(10,2);
---------------------------------------------------------------Mahesh 21Sep2023------------------------------------------------------------------------------
alter table  if exists "ObEncounter" 
add column if not exists "LSCS" TEXT;
---------------------------------------------------------------Radhika 22Sep2023-----------------------------------------------------------------------------
alter table if exists "GynEncounter"
add column if not exists "Reminder" text;

alter table if exists "ObEncounter"
add column if not exists "Reminder" text;
---------------------------------------------------------------Chandana 22Sep2023-----------------------------------------------------------------------------
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'dietGuideLines'
            where "Url" ilike '%/diet-guidelines%';
        END IF ;
    END
   $$ ;
   
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'orderPrescription'
            where "Url" ilike '%/app/diet-plan-encounter/:id/:type/order-prescription%';
        END IF ;
    END
   $$ ;
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'referralForm'
            where "Url" ilike '%/app/diet-plan-encounter/:id/:type/referral-form%';
        END IF ;
    END
   $$ ;
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'specialFeature'
            where "Url" ilike '%/app/diet-plan-encounter/:id/:type/special-feature%';
        END IF ;
    END
   $$ ;
   
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'referralForm'
            where "Url" ilike '%/app/diet-plan-encounter/:id/:type/cross-consultation%';
        END IF ;
    END
   $$ ;
---------------------------------------------------------------------Tej 25Sep2023-------------------------------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_FetchDoctor_With_Availability_Specialization_Op"(character varying, integer, integer, character varying);

CREATE OR REPLACE FUNCTION public."udf_FetchDoctor_With_Availability_Specialization_Op"(
	filter character varying DEFAULT NULL::text,
	"locationId" integer DEFAULT NULL::integer,
	"consultationTypeId" integer DEFAULT NULL::integer,
	"appointmentDate" character varying DEFAULT NULL::text)
    RETURNS TABLE("ProviderAvailabilityId" integer, "FullName" character varying,"DoctorType" char, "DepartmentName" character varying, "DepartmentId" integer, "ProviderId" integer, "SpecializationId" integer, "SpecializationName" character varying, "LocationId" integer, "ConsultationTypeId" integer, "ProviderSpecializationId" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

SELECT DISTINCT  on (pr2."ProviderId", s."SpecializationId") prl."ProviderAvailabilityId" ,pr2."FullName", pr2."DoctorType" 
, d."DepartmentName" , d."DepartmentId" 
,pr2."ProviderId"
, s. "SpecializationId", s."SpecializationName"
, CMT."LocationId", prl."ConsultationTypeId",  pr2."ProviderId" || ',' || s."SpecializationId" AS "ProviderSpecializationId"
                           FROM "ProviderAvailability" prl
						  left Join "DoctorSpecializationMap" LSM on LSM."ProviderId" = prl."ProviderId"  and LSM."SpecializationId" = 																				prl."SpecializationId" and LSM."ConsultationTypeId" = prl."ConsultationTypeId"
						  left join "DoctorSpecializationChargeModuleDetails" DSCD on DSCD."ReferenceId" = LSM."DoctorSpecializationMapId"
						  left join "DoctorSpecializationChargeModuleCategory" DSCC on DSCC."DoctorSpecializationChargeModuleCategoryId" = 																			DSCD."DoctorSpecializationChargeModuleCategoryId"
						 left  join "ChargeModuleTemplate" CMT on CMT."ChargeModuleTemplateId" = DSCC."ChargeModuleTemplateId"
                         left  JOIN "Provider" pr2 on pr2."ProviderId" = LSM."ProviderId" and pr2."Active" is true
						   join "Account" pa on pa."ReferenceId" = pr2."ProviderId" and pa."Active" is true and pa."RoleId" = 3
						  left JOin "LocationAccountMap" LAM on LAM."AccountId" = pa."AccountId" and LAM."Active" IS TRUE
						   join "Specialization" s on s."SpecializationId" = ANY (pr2."Specializations")
                           JOIN "Location" pral on pral."LocationId" = CMT."LocationId" AND pral."Active" IS TRUE
                           JOIN "Practice" pra on pra."PracticeId" = pral."PracticeId" AND pra."Active" IS TRUE
						   JOIN "Department" d on d."DepartmentId" = pr2."DepartmentId" 
						   where pr2."Active" is true and CMT."LocationId" = "locationId"  and s."Active" = true and prl."Active" is true
						   --and CMT."StartDate"::date <= "appointmentDate"::date and CMT."EndDate"::date >= "appointmentDate"::date 
						   and "IsInUse" is true
 
and case when "filter" is null then 1=1 else  TRIM(UPPER(pr2."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(s."SpecializationName")) ilike'%'|| "filter"||'%' end 
and case when "consultationTypeId" is null then 1=1 else  prl."ConsultationTypeId" = "consultationTypeId" end
and case when "appointmentDate" is null then CMT."StartDate"::date <= current_date::date and CMT."EndDate"::date >= current_date::date else CMT."StartDate"::date <= "appointmentDate"::date and CMT."EndDate"::date >= "appointmentDate"::date end
	
	--and	case when "locationId" is null then 1=1 else  LAM."LocationId"  = "LocationId" end
	--order by "FullName" asc
;
END
$BODY$;
---------------------------------------------------------------------Rajasekhar25Sep2023-------------------------------------------------------------------------
alter table if exists "ObEncounter" 
add column if  not exists "AdmissionDetails" text;

---------------------------------------------------------------------Mahesh 25Sep2023----------------------------------------------------------------------------
alter table  if exists "ObEncounter" add column if not exists "IUFD" TEXT;
---------------------------------------------------------------Subramanyam 25Sep2023-----------------------------------------------------------------------------
alter table if exists "ObEncounter" 
add column if not exists "DoctorsReview" Text;
---------------------------------------------------------------------Tej 26Sep2023-------------------------------------------------------------------------------
alter table if exists "Account" 
add column if not exists "CallerUser" character varying;
---------------------------------------------------------------------kalyan 26Sep2023-----------------------------------------------------------------------------

alter table if exists "ExternalLabAgency"
add column if not exists "AgencyCode" character varying(255) COLLATE pg_catalog."default" NOT NULL,
add column if not exists "Address" text COLLATE pg_catalog."default",
add column if not exists "URL" character varying(255) COLLATE pg_catalog."default" NOT NULL;

CREATE SEQUENCE IF NOT EXISTS "ExternalLabAgencyDetail_ExternalLabAgencyDetailId_seq";
CREATE TABLE IF NOT EXISTS public."ExternalLabAgencyDetail"
(
    "ExternalLabAgencyDetailId" integer NOT NULL DEFAULT nextval('"ExternalLabAgencyDetail_ExternalLabAgencyDetailId_seq"'::regclass),
    "ExternalLabAgencyId" integer NOT NULL,
    "LabMainDetailId" integer NOT NULL,
    "LocationId" integer NOT NULL,
    "Amount" numeric(8,2) NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp without time zone,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_ExternalLabAgencyDetail_ExternalLabAgencyDetailId" PRIMARY KEY ("ExternalLabAgencyDetailId"),
    CONSTRAINT "FK_ExternalLabAgency_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabAgency_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabAgency_LabMainDetailId_fkey" FOREIGN KEY ("LabMainDetailId")
        REFERENCES public."LabMainDetail" ("LabMainDetailId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabAgency_ExternalLabAgencyId_fkey" FOREIGN KEY ("ExternalLabAgencyId")
        REFERENCES public."ExternalLabAgency" ("ExternalLabAgencyId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabAgency_LocationId" FOREIGN KEY ("LocationId")
        REFERENCES public."Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);
CREATE SEQUENCE IF NOT EXISTS "ExternalLabTransfer_ExternalLabTransferId_seq";

CREATE TABLE IF NOT EXISTS public."ExternalLabTransfer"
(
    "ExternalLabTransferId" integer NOT NULL DEFAULT nextval('"ExternalLabTransfer_ExternalLabTransferId_seq"'::regclass),
    "TransferNumber" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "ExternalLabAgencyId" integer NOT NULL,
    "NewLabBookingDetailId" integer NOT NULL,
    "LabSampleCollectionDetailId" integer NOT NULL,
    "FromLocationId" integer NOT NULL,
    "Comments" text COLLATE pg_catalog."default",
    "TransferredBy" integer NOT NULL,
    "TransferredDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp without time zone,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_ExternalLabTransfer_ExternalLabTransferId" PRIMARY KEY ("ExternalLabTransferId"),
    CONSTRAINT "FK_ExternalLabTransfer_ExternalLabAgencyId" FOREIGN KEY ("ExternalLabAgencyId")
        REFERENCES public."ExternalLabAgency" ("ExternalLabAgencyId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabTransfer_NewLabBookingDetailId" FOREIGN KEY ("NewLabBookingDetailId")
        REFERENCES public."NewLabBookingDetail" ("NewLabBookingDetailId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabTransfer_LabSampleCollectionDetailId" FOREIGN KEY ("LabSampleCollectionDetailId")
        REFERENCES public."LabSampleCollectionDetail" ("LabSampleCollectionDetailId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabTransfer_FromLocationId" FOREIGN KEY ("FromLocationId")
        REFERENCES public."Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabTransfer_TransferredBy" FOREIGN KEY ("TransferredBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabTransfer_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);